code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def build_extension(self, ext_name: str, configs: Mapping[str, Any]) -> Extension:
"""
Build extension from a string name, then return an instance using the given `configs`.
Arguments:
ext_name: Name of extension as a string.
configs: Configuration settings for extension... |
Build extension from a string name, then return an instance using the given `configs`.
Arguments:
ext_name: Name of extension as a string.
configs: Configuration settings for extension.
Returns:
An instance of the extension with the given configuration sett... | build_extension | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def reset(self) -> Markdown:
"""
Resets all state variables to prepare the parser instance for new input.
Called once upon creation of a class instance. Should be called manually between calls
to [`Markdown.convert`][markdown.Markdown.convert].
"""
self.htmlStash.reset()... |
Resets all state variables to prepare the parser instance for new input.
Called once upon creation of a class instance. Should be called manually between calls
to [`Markdown.convert`][markdown.Markdown.convert].
| reset | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def set_output_format(self, format: str) -> Markdown:
"""
Set the output format for the class instance.
Arguments:
format: Must be a known value in `Markdown.output_formats`.
"""
self.output_format = format.lower().rstrip('145') # ignore number
try:
... |
Set the output format for the class instance.
Arguments:
format: Must be a known value in `Markdown.output_formats`.
| set_output_format | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def is_block_level(self, tag: Any) -> bool:
"""
Check if the given `tag` is a block level HTML tag.
Returns `True` for any string listed in `Markdown.block_level_elements`. A `tag` which is
not a string always returns `False`.
"""
if isinstance(tag, str):
re... |
Check if the given `tag` is a block level HTML tag.
Returns `True` for any string listed in `Markdown.block_level_elements`. A `tag` which is
not a string always returns `False`.
| is_block_level | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def convert(self, source: str) -> str:
"""
Convert a Markdown string to a string in the specified output format.
Arguments:
source: Markdown formatted text as Unicode or ASCII string.
Returns:
A string in the specified output format.
Markdown parsing ta... |
Convert a Markdown string to a string in the specified output format.
Arguments:
source: Markdown formatted text as Unicode or ASCII string.
Returns:
A string in the specified output format.
Markdown parsing takes place in five steps:
1. A bunch of [`... | convert | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def convertFile(
self,
input: str | BinaryIO | None = None,
output: str | BinaryIO | None = None,
encoding: str | None = None,
) -> Markdown:
"""
Converts a Markdown file and returns the HTML as a Unicode string.
Decodes the file using the provided encoding (... |
Converts a Markdown file and returns the HTML as a Unicode string.
Decodes the file using the provided encoding (defaults to `utf-8`),
passes the file content to markdown, and outputs the HTML to either
the provided stream or the file with provided name, using the same
encoding... | convertFile | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def markdownFromFile(**kwargs: Any):
"""
Read Markdown text from a file and write output to a file or a stream.
This is a shortcut function which initializes an instance of [`Markdown`][markdown.Markdown],
and calls the [`convertFile`][markdown.Markdown.convertFile] method rather than
[`convert`][m... |
Read Markdown text from a file and write output to a file or a stream.
This is a shortcut function which initializes an instance of [`Markdown`][markdown.Markdown],
and calls the [`convertFile`][markdown.Markdown.convertFile] method rather than
[`convert`][markdown.Markdown.convert].
Keyword argu... | markdownFromFile | python | Python-Markdown/markdown | markdown/core.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py | BSD-3-Clause |
def line_offset(self) -> int:
"""Returns char index in `self.rawdata` for the start of the current line. """
for ii in range(len(self.lineno_start_cache)-1, self.lineno-1):
last_line_start_pos = self.lineno_start_cache[ii]
lf_pos = self.rawdata.find('\n', last_line_start_pos)
... | Returns char index in `self.rawdata` for the start of the current line. | line_offset | python | Python-Markdown/markdown | markdown/htmlparser.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/htmlparser.py | BSD-3-Clause |
def at_line_start(self) -> bool:
"""
Returns True if current position is at start of line.
Allows for up to three blank spaces at start of line.
"""
if self.offset == 0:
return True
if self.offset > 3:
return False
# Confirm up to first 3 ... |
Returns True if current position is at start of line.
Allows for up to three blank spaces at start of line.
| at_line_start | python | Python-Markdown/markdown | markdown/htmlparser.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/htmlparser.py | BSD-3-Clause |
def get_endtag_text(self, tag: str) -> str:
"""
Returns the text of the end tag.
If it fails to extract the actual text from the raw data, it builds a closing tag with `tag`.
"""
# Attempt to extract actual tag from raw source text
start = self.line_offset + self.offset
... |
Returns the text of the end tag.
If it fails to extract the actual text from the raw data, it builds a closing tag with `tag`.
| get_endtag_text | python | Python-Markdown/markdown | markdown/htmlparser.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/htmlparser.py | BSD-3-Clause |
def build_inlinepatterns(md: Markdown, **kwargs: Any) -> util.Registry[InlineProcessor]:
"""
Build the default set of inline patterns for Markdown.
The order in which processors and/or patterns are applied is very important - e.g. if we first replace
`http://.../` links with `<a>` tags and _then_ try t... |
Build the default set of inline patterns for Markdown.
The order in which processors and/or patterns are applied is very important - e.g. if we first replace
`http://.../` links with `<a>` tags and _then_ try to replace inline HTML, we would end up with a mess. So, we
apply the expressions in the foll... | build_inlinepatterns | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def __init__(self, pattern: str, md: Markdown | None = None):
"""
Create an instant of an inline pattern.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
`... |
Create an instant of an inline pattern.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
`self.md` on the class instance.
| __init__ | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def unescape(self, text: str) -> str:
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.md.treeprocessors['inline'].stashed_nodes
except KeyError: # pragma: no cover
return text
def get_stash(m):
id = m.group(1)
... | Return unescaped text given text with an inline placeholder. | unescape | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def __init__(self, pattern: str, md: Markdown | None = None):
"""
Create an instant of an inline processor.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
... |
Create an instant of an inline processor.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
`self.md` on the class instance.
| __init__ | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[str | None, int, int]:
"""
If the character matched by `group(1)` of a pattern is in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS]
then return the integer representing the character's Unicode code point (as returned by [`ord`][]) w... |
If the character matched by `group(1)` of a pattern is in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS]
then return the integer representing the character's Unicode code point (as returned by [`ord`][]) wrapped
in [`util.STX`][markdown.util.STX] and [`util.ETX`][markdown.util.ETX].
... | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def __init__(self, pattern: str, tag: str):
"""
Create an instant of an simple tag pattern.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
"""
Pattern.__init__(self, pattern)
self.tag = tag
""" The t... |
Create an instant of an simple tag pattern.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
| __init__ | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str]) -> etree.Element:
"""
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(3)` of a
matching pattern as the Element's text.
"""
el = etree.Element(self.tag)
el.text = m.group(3)
return el |
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(3)` of a
matching pattern as the Element's text.
| handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def __init__(self, pattern: str, tag: str):
"""
Create an instant of an simple tag processor.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
"""
InlineProcessor.__init__(self, pattern)
self.tag = tag
... |
Create an instant of an simple tag processor.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
| __init__ | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
"""
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(2)` of a
matching pattern as the Element's text.
"""
el = etree.Element(self.tag... |
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(2)` of a
matching pattern as the Element's text.
| handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str, int, int]:
"""
If the match contains `group(3)` of a pattern, then return a `code`
[`Element`][xml.etree.ElementTree.Element] which contains HTML escaped text (with
[`code_escape`][markdown.util.code_escape]... |
If the match contains `group(3)` of a pattern, then return a `code`
[`Element`][xml.etree.ElementTree.Element] which contains HTML escaped text (with
[`code_escape`][markdown.util.code_escape]) as an [`AtomicString`][markdown.util.AtomicString].
If the match does not contain `group(3)`... | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str]) -> etree.Element:
"""
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(3)</tag2>group(4)</tag2>` where `group(4)` is optional.
"""
tag1, tag2 = self.tag.split(",")
el1 = etree.Element(tag1)
... |
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(3)</tag2>group(4)</tag2>` where `group(4)` is optional.
| handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
"""
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(2)</tag2>group(3)</tag2>` where `group(3)` is optional.
"""
tag1, tag2 = self.t... |
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(2)</tag2>group(3)</tag2>` where `group(3)` is optional.
| handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]:
""" Store the text of `group(1)` of a pattern and return a placeholder string. """
rawhtml = self.backslash_unescape(self.unescape(m.group(1)))
place_holder = self.md.htmlStash.store(rawhtml)
return place_holder,... | Store the text of `group(1)` of a pattern and return a placeholder string. | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def backslash_unescape(self, text: str) -> str:
""" Return text with backslash escapes undone (backslashes are restored). """
try:
RE = self.md.treeprocessors['unescape'].RE
except KeyError: # pragma: no cover
return text
def _unescape(m: re.Match[str]) -> str:
... | Return text with backslash escapes undone (backslashes are restored). | backslash_unescape | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def build_double2(self, m: re.Match[str], tags: str, idx: int) -> etree.Element:
"""Return double tags (variant 2): `<strong>text <em>text</em></strong>`."""
tag1, tag2 = tags.split(",")
el1 = etree.Element(tag1)
el2 = etree.Element(tag2)
text = m.group(2)
self.parse_sub... | Return double tags (variant 2): `<strong>text <em>text</em></strong>`. | build_double2 | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def parse_sub_patterns(
self, data: str, parent: etree.Element, last: etree.Element | None, idx: int
) -> None:
"""
Parses sub patterns.
`data`: text to evaluate.
`parent`: Parent to attach text and sub elements to.
`last`: Last appended child to parent. Can also b... |
Parses sub patterns.
`data`: text to evaluate.
`parent`: Parent to attach text and sub elements to.
`last`: Last appended child to parent. Can also be None if parent has no children.
`idx`: Current pattern index that was used to evaluate the parent.
| parse_sub_patterns | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
""" Return an `a` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. """
text, index, handled = self.getText(data, m.end(0))
if not handled:
return None, None,... | Return an `a` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def getLink(self, data: str, index: int) -> tuple[str, str | None, int, bool]:
"""Parse data between `()` of `[Text]()` allowing recursive `()`. """
href = ''
title: str | None = None
handled = False
m = self.RE_LINK.match(data, pos=index)
if m and m.group(1):
... | Parse data between `()` of `[Text]()` allowing recursive `()`. | getLink | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def getText(self, data: str, index: int) -> tuple[str, int, bool]:
"""Parse the content between `[]` of the start of an image or link
resolving nested square brackets.
"""
bracket_count = 1
text = []
for pos in range(index, len(data)):
c = data[pos]
... | Parse the content between `[]` of the start of an image or link
resolving nested square brackets.
| getText | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
""" Return an `img` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. """
text, index, handled = self.getText(data, m.end(0))
if not handled:
return None, None... | Return an `img` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
"""
Return [`Element`][xml.etree.ElementTree.Element] returned by `makeTag` method or `(None, None, None)`.
"""
text, index, handled = self.getText(data, m.end(0))
if not h... |
Return [`Element`][xml.etree.ElementTree.Element] returned by `makeTag` method or `(None, None, None)`.
| handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def evalId(self, data: str, index: int, text: str) -> tuple[str | None, int, bool]:
"""
Evaluate the id portion of `[ref][id]`.
If `[ref][]` use `[ref]`.
"""
m = self.RE_LINK.match(data, pos=index)
if not m:
return None, index, False
else:
... |
Evaluate the id portion of `[ref][id]`.
If `[ref][]` use `[ref]`.
| evalId | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def makeTag(self, href: str, title: str, text: str) -> etree.Element:
""" Return an `a` [`Element`][xml.etree.ElementTree.Element]. """
el = etree.Element('a')
el.set('href', href)
if title:
el.set('title', title)
el.text = text
return el | Return an `a` [`Element`][xml.etree.ElementTree.Element]. | makeTag | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def makeTag(self, href: str, title: str, text: str) -> etree.Element:
""" Return an `img` [`Element`][xml.etree.ElementTree.Element]. """
el = etree.Element("img")
el.set("src", href)
if title:
el.set("title", title)
el.set("alt", self.unescape(text))
return e... | Return an `img` [`Element`][xml.etree.ElementTree.Element]. | makeTag | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
""" Return an `a` [`Element`][xml.etree.ElementTree.Element] of `group(1)`. """
el = etree.Element("a")
el.set('href', self.unescape(m.group(1)))
el.text = util.AtomicString(m.group(1))
return e... | Return an `a` [`Element`][xml.etree.ElementTree.Element] of `group(1)`. | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
""" Return an [`Element`][xml.etree.ElementTree.Element] containing a `mailto` link of `group(1)`. """
el = etree.Element('a')
email = self.unescape(m.group(1))
if email.startswith("mailto:"):
... | Return an [`Element`][xml.etree.ElementTree.Element] containing a `mailto` link of `group(1)`. | handleMatch | python | Python-Markdown/markdown | markdown/inlinepatterns.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/inlinepatterns.py | BSD-3-Clause |
def build_postprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Postprocessor]:
""" Build the default postprocessors for Markdown. """
postprocessors = util.Registry()
postprocessors.register(RawHtmlPostprocessor(md), 'raw_html', 30)
postprocessors.register(AndSubstitutePostprocessor(), 'amp_subs... | Build the default postprocessors for Markdown. | build_postprocessors | python | Python-Markdown/markdown | markdown/postprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/postprocessors.py | BSD-3-Clause |
def run(self, text: str) -> str:
""" Iterate over html stash and restore html. """
def substitute_match(m: re.Match[str]) -> str:
if key := m.group(1):
wrapped = True
else:
key = m.group(2)
wrapped = False
if (key := int... | Iterate over html stash and restore html. | run | python | Python-Markdown/markdown | markdown/postprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/postprocessors.py | BSD-3-Clause |
def isblocklevel(self, html: str) -> bool:
""" Check is block of HTML is block-level. """
m = self.BLOCK_LEVEL_REGEX.match(html)
if m:
if m.group(1)[0] in ('!', '?', '@', '%'):
# Comment, PHP etc...
return True
return self.md.is_block_level... | Check is block of HTML is block-level. | isblocklevel | python | Python-Markdown/markdown | markdown/postprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/postprocessors.py | BSD-3-Clause |
def build_preprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Preprocessor]:
""" Build and return the default set of preprocessors used by Markdown. """
preprocessors = util.Registry()
preprocessors.register(NormalizeWhitespace(md), 'normalize_whitespace', 30)
preprocessors.register(HtmlBlockPre... | Build and return the default set of preprocessors used by Markdown. | build_preprocessors | python | Python-Markdown/markdown | markdown/preprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/preprocessors.py | BSD-3-Clause |
def assertMarkdownRenders(self, source, expected, expected_attrs=None, **kwargs):
"""
Test that source Markdown text renders to expected output with given keywords.
`expected_attrs` accepts a `dict`. Each key should be the name of an attribute
on the `Markdown` instance and the value sh... |
Test that source Markdown text renders to expected output with given keywords.
`expected_attrs` accepts a `dict`. Each key should be the name of an attribute
on the `Markdown` instance and the value should be the expected value after
the source text is parsed by Markdown. After the exp... | assertMarkdownRenders | python | Python-Markdown/markdown | markdown/test_tools.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/test_tools.py | BSD-3-Clause |
def _normalize_whitespace(text):
""" Normalize whitespace for a string of HTML using `tidylib`. """
output, errors = tidylib.tidy_fragment(text, options={
'drop_empty_paras': 0,
'fix_backslash': 0,
'fix_bad_comments': 0,
'fix_uri': 0,
'join_styles': 0,
'lower_lite... | Normalize whitespace for a string of HTML using `tidylib`. | _normalize_whitespace | python | Python-Markdown/markdown | markdown/test_tools.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/test_tools.py | BSD-3-Clause |
def build_treeprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Treeprocessor]:
""" Build the default `treeprocessors` for Markdown. """
treeprocessors = util.Registry()
treeprocessors.register(InlineProcessor(md), 'inline', 20)
treeprocessors.register(PrettifyTreeprocessor(md), 'prettify', 10)
... | Build the default `treeprocessors` for Markdown. | build_treeprocessors | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def isString(s: object) -> bool:
""" Return `True` if object is a string but not an [`AtomicString`][markdown.util.AtomicString]. """
if not isinstance(s, util.AtomicString):
return isinstance(s, str)
return False | Return `True` if object is a string but not an [`AtomicString`][markdown.util.AtomicString]. | isString | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def __findPlaceholder(self, data: str, index: int) -> tuple[str | None, int]:
"""
Extract id from data string, start from index.
Arguments:
data: String.
index: Index, from which we start search.
Returns:
Placeholder id and string index, after the fo... |
Extract id from data string, start from index.
Arguments:
data: String.
index: Index, from which we start search.
Returns:
Placeholder id and string index, after the found placeholder.
| __findPlaceholder | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def __handleInline(self, data: str, patternIndex: int = 0) -> str:
"""
Process string with inline patterns and replace it with placeholders.
Arguments:
data: A line of Markdown text.
patternIndex: The index of the `inlinePattern` to start with.
Returns:
... |
Process string with inline patterns and replace it with placeholders.
Arguments:
data: A line of Markdown text.
patternIndex: The index of the `inlinePattern` to start with.
Returns:
String with placeholders.
| __handleInline | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def __processElementText(self, node: etree.Element, subnode: etree.Element, isText: bool = True) -> None:
"""
Process placeholders in `Element.text` or `Element.tail`
of Elements popped from `self.stashed_nodes`.
Arguments:
node: Parent node.
subnode: Processing ... |
Process placeholders in `Element.text` or `Element.tail`
of Elements popped from `self.stashed_nodes`.
Arguments:
node: Parent node.
subnode: Processing node.
isText: Boolean variable, True - it's text, False - it's a tail.
| __processElementText | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def __processPlaceholders(
self,
data: str | None,
parent: etree.Element,
isText: bool = True
) -> list[tuple[etree.Element, list[str]]]:
"""
Process string with placeholders and generate `ElementTree` tree.
Arguments:
data: String with placeholde... |
Process string with placeholders and generate `ElementTree` tree.
Arguments:
data: String with placeholders instead of `ElementTree` elements.
parent: Element, which contains processing inline data.
isText: Boolean variable, True - it's text, False - it's a tail.
... | __processPlaceholders | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def __applyPattern(
self,
pattern: inlinepatterns.Pattern,
data: str,
patternIndex: int,
startIndex: int = 0
) -> tuple[str, bool, int]:
"""
Check if the line fits the pattern, create the necessary
elements, add it to `stashed_nodes`.
Argument... |
Check if the line fits the pattern, create the necessary
elements, add it to `stashed_nodes`.
Arguments:
data: The text to be processed.
pattern: The pattern to be checked.
patternIndex: Index of current pattern.
startIndex: String index, from wh... | __applyPattern | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def run(self, tree: etree.Element, ancestors: list[str] | None = None) -> etree.Element:
"""Apply inline patterns to a parsed Markdown tree.
Iterate over `Element`, find elements with inline tag, apply inline
patterns and append newly created Elements to tree. To avoid further
processi... | Apply inline patterns to a parsed Markdown tree.
Iterate over `Element`, find elements with inline tag, apply inline
patterns and append newly created Elements to tree. To avoid further
processing of string with inline patterns, instead of normal string,
use subclass [`AtomicString`][m... | run | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def _prettifyETree(self, elem: etree.Element) -> None:
""" Recursively add line breaks to `ElementTree` children. """
i = "\n"
if self.md.is_block_level(elem.tag) and elem.tag not in ['code', 'pre']:
if (not elem.text or not elem.text.strip()) \
and len(elem) and... | Recursively add line breaks to `ElementTree` children. | _prettifyETree | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def run(self, root: etree.Element) -> None:
""" Add line breaks to `Element` object and its children. """
self._prettifyETree(root)
# Do `<br />`'s separately as they are often in the middle of
# inline content and missed by `_prettifyETree`.
brs = root.iter('br')
for br... | Add line breaks to `Element` object and its children. | run | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def run(self, root: etree.Element) -> None:
""" Loop over all elements and unescape all text. """
for elem in root.iter():
# Unescape text content
if elem.text and not elem.tag == 'code':
elem.text = self.unescape(elem.text)
# Unescape tail content
... | Loop over all elements and unescape all text. | run | python | Python-Markdown/markdown | markdown/treeprocessors.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/treeprocessors.py | BSD-3-Clause |
def get_installed_extensions():
""" Return all entry_points in the `markdown.extensions` group. """
if sys.version_info >= (3, 10):
from importlib import metadata
else: # `<PY310` use backport
import importlib_metadata as metadata
# Only load extension entry_points once.
return meta... | Return all entry_points in the `markdown.extensions` group. | get_installed_extensions | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def deprecated(message: str, stacklevel: int = 2):
"""
Raise a [`DeprecationWarning`][] when wrapped function/method is called.
Usage:
```python
@deprecated("This method will be removed in version X; use Y instead.")
def some_method():
pass
```
"""
def wrapper(func):
... |
Raise a [`DeprecationWarning`][] when wrapped function/method is called.
Usage:
```python
@deprecated("This method will be removed in version X; use Y instead.")
def some_method():
pass
```
| deprecated | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def parseBoolValue(value: str | None, fail_on_errors: bool = True, preserve_none: bool = False) -> bool | None:
"""Parses a string representing a boolean value. If parsing was successful,
returns `True` or `False`. If `preserve_none=True`, returns `True`, `False`,
or `None`. If parsing was not success... | Parses a string representing a boolean value. If parsing was successful,
returns `True` or `False`. If `preserve_none=True`, returns `True`, `False`,
or `None`. If parsing was not successful, raises `ValueError`, or, if
`fail_on_errors=False`, returns `None`. | parseBoolValue | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def store(self, html: str | etree.Element) -> str:
"""
Saves an HTML segment for later reinsertion. Returns a
placeholder string that needs to be inserted into the
document.
Keyword arguments:
html: An html segment.
Returns:
A placeholder string... |
Saves an HTML segment for later reinsertion. Returns a
placeholder string that needs to be inserted into the
document.
Keyword arguments:
html: An html segment.
Returns:
A placeholder string.
| store | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def store_tag(self, tag: str, attrs: dict[str, str], left_index: int, right_index: int) -> str:
"""Store tag data and return a placeholder."""
self.tag_data.append({'tag': tag, 'attrs': attrs,
'left_index': left_index,
'right_index': right_inde... | Store tag data and return a placeholder. | store_tag | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def get_index_for_name(self, name: str) -> int:
"""
Return the index of the given name.
"""
if name in self:
self._sort()
return self._priority.index(
[x for x in self._priority if x.name == name][0]
)
raise ValueError('No item ... |
Return the index of the given name.
| get_index_for_name | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def register(self, item: _T, name: str, priority: float) -> None:
"""
Add an item to the registry with the given name and priority.
Arguments:
item: The item being registered.
name: A string used to reference the item.
priority: An integer or float used to so... |
Add an item to the registry with the given name and priority.
Arguments:
item: The item being registered.
name: A string used to reference the item.
priority: An integer or float used to sort against all items.
If an item is registered with a "name" which a... | register | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def deregister(self, name: str, strict: bool = True) -> None:
"""
Remove an item from the registry.
Set `strict=False` to fail silently. Otherwise a [`ValueError`][] is raised for an unknown `name`.
"""
try:
index = self.get_index_for_name(name)
del self.... |
Remove an item from the registry.
Set `strict=False` to fail silently. Otherwise a [`ValueError`][] is raised for an unknown `name`.
| deregister | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def _sort(self) -> None:
"""
Sort the registry by priority from highest to lowest.
This method is called internally and should never be explicitly called.
"""
if not self._is_sorted:
self._priority.sort(key=lambda item: item.priority, reverse=True)
self._... |
Sort the registry by priority from highest to lowest.
This method is called internally and should never be explicitly called.
| _sort | python | Python-Markdown/markdown | markdown/util.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/util.py | BSD-3-Clause |
def _get_version(version_info):
" Returns a PEP 440-compliant version number from `version_info`. "
assert len(version_info) == 5
assert version_info[3] in ('dev', 'alpha', 'beta', 'rc', 'final')
parts = 2 if version_info[2] == 0 else 3
v = '.'.join(map(str, version_info[:parts]))
if version_i... | Returns a PEP 440-compliant version number from `version_info`. | _get_version | python | Python-Markdown/markdown | markdown/__meta__.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/__meta__.py | BSD-3-Clause |
def __init__(self, **kwargs):
""" Initiate Extension and set up configs. """
self.config = {
'glossary': [
{},
'A dictionary where the `key` is the abbreviation and the `value` is the definition.'
"Default: `{}`"
],
}
... | Initiate Extension and set up configs. | __init__ | python | Python-Markdown/markdown | markdown/extensions/abbr.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/abbr.py | BSD-3-Clause |
def load_glossary(self, dictionary: dict[str, str]):
"""Adds `dictionary` to our glossary. Any abbreviations that already exist will be overwritten."""
if dictionary:
self.glossary = {**dictionary, **self.glossary} | Adds `dictionary` to our glossary. Any abbreviations that already exist will be overwritten. | load_glossary | python | Python-Markdown/markdown | markdown/extensions/abbr.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/abbr.py | BSD-3-Clause |
def iter_element(self, el: etree.Element, parent: etree.Element | None = None) -> None:
''' Recursively iterate over elements, run regex on text and wrap matches in `abbr` tags. '''
for child in reversed(el):
self.iter_element(child, el)
if text := el.text:
if not isinsta... | Recursively iterate over elements, run regex on text and wrap matches in `abbr` tags. | iter_element | python | Python-Markdown/markdown | markdown/extensions/abbr.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/abbr.py | BSD-3-Clause |
def run(self, root: etree.Element) -> etree.Element | None:
''' Step through tree to find known abbreviations. '''
if not self.abbrs:
# No abbreviations defined. Skip running processor.
return
# Build and compile regex
abbr_list = list(self.abbrs.keys())
a... | Step through tree to find known abbreviations. | run | python | Python-Markdown/markdown | markdown/extensions/abbr.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/abbr.py | BSD-3-Clause |
def run(self, parent: etree.Element, blocks: list[str]) -> bool:
"""
Find and remove all abbreviation references from the text.
Each reference is added to the abbreviation collection.
"""
block = blocks.pop(0)
m = self.RE.search(block)
if m:
abbr = m.... |
Find and remove all abbreviation references from the text.
Each reference is added to the abbreviation collection.
| run | python | Python-Markdown/markdown | markdown/extensions/abbr.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/abbr.py | BSD-3-Clause |
def parse_content(self, parent: etree.Element, block: str) -> tuple[etree.Element | None, str, str]:
"""Get sibling admonition.
Retrieve the appropriate sibling element. This can get tricky when
dealing with lists.
"""
old_block = block
the_rest = ''
# We alre... | Get sibling admonition.
Retrieve the appropriate sibling element. This can get tricky when
dealing with lists.
| parse_content | python | Python-Markdown/markdown | markdown/extensions/admonition.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/admonition.py | BSD-3-Clause |
def get_attrs_and_remainder(attrs_string: str) -> tuple[list[tuple[str, str]], str]:
""" Parse attribute list and return a list of attribute tuples.
Additionally, return any text that remained after a curly brace. In typical cases, its presence
should mean that the input does not match the intended attribu... | Parse attribute list and return a list of attribute tuples.
Additionally, return any text that remained after a curly brace. In typical cases, its presence
should mean that the input does not match the intended attribute list syntax.
| get_attrs_and_remainder | python | Python-Markdown/markdown | markdown/extensions/attr_list.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/attr_list.py | BSD-3-Clause |
def assign_attrs(self, elem: Element, attrs_string: str, *, strict: bool = False) -> str:
""" Assign `attrs` to element.
If the `attrs_string` has an extra closing curly brace, the remaining text is returned.
The `strict` argument controls whether to still assign `attrs` if there is a remainin... | Assign `attrs` to element.
If the `attrs_string` has an extra closing curly brace, the remaining text is returned.
The `strict` argument controls whether to still assign `attrs` if there is a remaining `}`.
| assign_attrs | python | Python-Markdown/markdown | markdown/extensions/attr_list.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/attr_list.py | BSD-3-Clause |
def parse_hl_lines(expr: str) -> list[int]:
"""Support our syntax for emphasizing certain lines of code.
`expr` should be like '1 2' to emphasize lines 1 and 2 of a code block.
Returns a list of integers, the line numbers to emphasize.
"""
if not expr:
return []
try:
return lis... | Support our syntax for emphasizing certain lines of code.
`expr` should be like '1 2' to emphasize lines 1 and 2 of a code block.
Returns a list of integers, the line numbers to emphasize.
| parse_hl_lines | python | Python-Markdown/markdown | markdown/extensions/codehilite.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/codehilite.py | BSD-3-Clause |
def hilite(self, shebang: bool = True) -> str:
"""
Pass code to the [Pygments](https://pygments.org/) highlighter with
optional line numbers. The output should then be styled with CSS to
your liking. No styles are applied by default - only styling hooks
(i.e.: `<span class="k">`)... |
Pass code to the [Pygments](https://pygments.org/) highlighter with
optional line numbers. The output should then be styled with CSS to
your liking. No styles are applied by default - only styling hooks
(i.e.: `<span class="k">`).
returns : A string of html.
| hilite | python | Python-Markdown/markdown | markdown/extensions/codehilite.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/codehilite.py | BSD-3-Clause |
def _parseHeader(self) -> None:
"""
Determines language of a code block from shebang line and whether the
said line should be removed or left in place. If the shebang line
contains a path (even a single /) then it is assumed to be a real
shebang line and left alone. However, if n... |
Determines language of a code block from shebang line and whether the
said line should be removed or left in place. If the shebang line
contains a path (even a single /) then it is assumed to be a real
shebang line and left alone. However, if no path is given
(e.i.: `#!python` o... | _parseHeader | python | Python-Markdown/markdown | markdown/extensions/codehilite.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/codehilite.py | BSD-3-Clause |
def run(self, root: etree.Element) -> None:
""" Find code blocks and store in `htmlStash`. """
blocks = root.iter('pre')
for block in blocks:
if len(block) == 1 and block[0].tag == 'code':
local_config = self.config.copy()
text = block[0].text
... | Find code blocks and store in `htmlStash`. | run | python | Python-Markdown/markdown | markdown/extensions/codehilite.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/codehilite.py | BSD-3-Clause |
def extendMarkdown(self, md):
""" Add an instance of `DefListProcessor` to `BlockParser`. """
md.parser.blockprocessors.register(DefListIndentProcessor(md.parser), 'defindent', 85)
md.parser.blockprocessors.register(DefListProcessor(md.parser), 'deflist', 25) | Add an instance of `DefListProcessor` to `BlockParser`. | extendMarkdown | python | Python-Markdown/markdown | markdown/extensions/def_list.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/def_list.py | BSD-3-Clause |
def extendMarkdown(self, md):
""" Add `FencedBlockPreprocessor` to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.register(FencedBlockPreprocessor(md, self.getConfigs()), 'fenced_code_block', 25) | Add `FencedBlockPreprocessor` to the Markdown instance. | extendMarkdown | python | Python-Markdown/markdown | markdown/extensions/fenced_code.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/fenced_code.py | BSD-3-Clause |
def run(self, lines: list[str]) -> list[str]:
""" Match and store Fenced Code Blocks in the `HtmlStash`. """
# Check for dependent extensions
if not self.checked_for_deps:
for ext in self.md.registeredExtensions:
if isinstance(ext, CodeHiliteExtension):
... | Match and store Fenced Code Blocks in the `HtmlStash`. | run | python | Python-Markdown/markdown | markdown/extensions/fenced_code.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/fenced_code.py | BSD-3-Clause |
def handle_attrs(self, attrs: Iterable[tuple[str, str]]) -> tuple[str, list[str], dict[str, Any]]:
""" Return tuple: `(id, [list, of, classes], {configs})` """
id = ''
classes = []
configs = {}
for k, v in attrs:
if k == 'id':
id = v
elif k... | Return tuple: `(id, [list, of, classes], {configs})` | handle_attrs | python | Python-Markdown/markdown | markdown/extensions/fenced_code.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/fenced_code.py | BSD-3-Clause |
def reset(self) -> None:
""" Clear footnotes on reset, and prepare for distinct document. """
self.footnotes: OrderedDict[str, str] = OrderedDict()
self.unique_prefix += 1
self.found_refs = {}
self.used_refs = set() | Clear footnotes on reset, and prepare for distinct document. | reset | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def unique_ref(self, reference: str, found: bool = False) -> str:
""" Get a unique reference if there are duplicates. """
if not found:
return reference
original_ref = reference
while reference in self.used_refs:
ref, rest = reference.split(self.get_separator(), ... | Get a unique reference if there are duplicates. | unique_ref | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def makeFootnotesDiv(self, root: etree.Element) -> etree.Element | None:
""" Return `div` of footnotes as `etree` Element. """
if not list(self.footnotes.keys()):
return None
div = etree.Element("div")
div.set('class', 'footnote')
etree.SubElement(div, "hr")
... | Return `div` of footnotes as `etree` Element. | makeFootnotesDiv | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def run(self, parent: etree.Element, blocks: list[str]) -> bool:
""" Find, set, and remove footnote definitions. """
block = blocks.pop(0)
m = self.RE.search(block)
if m:
id = m.group(1)
fn_blocks = [m.group(2)]
# Handle rest of block
ther... | Find, set, and remove footnote definitions. | run | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def detectTabbed(self, blocks: list[str]) -> list[str]:
""" Find indented text and remove indent before further processing.
Returns:
A list of blocks with indentation removed.
"""
fn_blocks = []
while blocks:
if blocks[0].startswith(' '*4):
... | Find indented text and remove indent before further processing.
Returns:
A list of blocks with indentation removed.
| detectTabbed | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def detab(self, block: str) -> str:
""" Remove one level of indent from a block.
Preserve lazily indented blocks by only removing indent from indented lines.
"""
lines = block.split('\n')
for i, line in enumerate(lines):
if line.startswith(' '*4):
lin... | Remove one level of indent from a block.
Preserve lazily indented blocks by only removing indent from indented lines.
| detab | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def add_duplicates(self, li: etree.Element, duplicates: int) -> None:
""" Adjust current `li` and add the duplicates: `fnref2`, `fnref3`, etc. """
for link in li.iter('a'):
# Find the link that needs to be duplicated.
if link.attrib.get('class', '') == 'footnote-backref':
... | Adjust current `li` and add the duplicates: `fnref2`, `fnref3`, etc. | add_duplicates | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def get_num_duplicates(self, li: etree.Element) -> int:
""" Get the number of duplicate refs of the footnote. """
fn, rest = li.attrib.get('id', '').split(self.footnotes.get_separator(), 1)
link_id = '{}ref{}{}'.format(fn, self.footnotes.get_separator(), rest)
return self.footnotes.found... | Get the number of duplicate refs of the footnote. | get_num_duplicates | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def handle_duplicates(self, parent: etree.Element) -> None:
""" Find duplicate footnotes and format and add the duplicates. """
for li in list(parent):
# Check number of duplicates footnotes and insert
# additional links if needed.
count = self.get_num_duplicates(li)
... | Find duplicate footnotes and format and add the duplicates. | handle_duplicates | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def run(self, root: etree.Element) -> None:
""" Crawl the footnote div and add missing duplicate footnotes. """
self.offset = 0
for div in root.iter('div'):
if div.attrib.get('class', '') == 'footnote':
# Footnotes should be under the first ordered list under
... | Crawl the footnote div and add missing duplicate footnotes. | run | python | Python-Markdown/markdown | markdown/extensions/footnotes.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py | BSD-3-Clause |
def run(self, doc: etree.Element) -> None:
"""Find and set values of attributes ({@key=value}). """
for el in doc.iter():
alt = el.get('alt', None)
if alt is not None:
el.set('alt', self.handleAttributes(el, alt))
if el.text and isString(el.text):
... | Find and set values of attributes ({@key=value}). | run | python | Python-Markdown/markdown | markdown/extensions/legacy_attrs.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/legacy_attrs.py | BSD-3-Clause |
def handleAttributes(self, el: etree.Element, txt: str) -> str:
""" Set attributes and return text without definitions. """
def attributeCallback(match: re.Match[str]):
el.set(match.group(1), match.group(2).replace('\n', ' '))
return ATTR_RE.sub(attributeCallback, txt) | Set attributes and return text without definitions. | handleAttributes | python | Python-Markdown/markdown | markdown/extensions/legacy_attrs.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/legacy_attrs.py | BSD-3-Clause |
def get_element(self) -> etree.Element:
""" Return element from `treebuilder` and reset `treebuilder` for later use. """
element = self.treebuilder.close()
self.treebuilder = etree.TreeBuilder()
return element | Return element from `treebuilder` and reset `treebuilder` for later use. | get_element | python | Python-Markdown/markdown | markdown/extensions/md_in_html.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/md_in_html.py | BSD-3-Clause |
def get_state(self, tag, attrs: Mapping[str, str]) -> Literal['block', 'span', 'off', None]:
""" Return state from tag and `markdown` attribute. One of 'block', 'span', or 'off'. """
md_attr = attrs.get('markdown', '0')
if md_attr == 'markdown':
# `<tag markdown>` is the same as `<ta... | Return state from tag and `markdown` attribute. One of 'block', 'span', or 'off'. | get_state | python | Python-Markdown/markdown | markdown/extensions/md_in_html.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/md_in_html.py | BSD-3-Clause |
def parse_element_content(self, element: etree.Element) -> None:
"""
Recursively parse the text content of an `etree` Element as Markdown.
Any block level elements generated from the Markdown will be inserted as children of the element in place
of the text content. All `markdown` attrib... |
Recursively parse the text content of an `etree` Element as Markdown.
Any block level elements generated from the Markdown will be inserted as children of the element in place
of the text content. All `markdown` attributes are removed. For any elements in which Markdown parsing has
bee... | parse_element_content | python | Python-Markdown/markdown | markdown/extensions/md_in_html.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/md_in_html.py | BSD-3-Clause |
def stash_to_string(self, text: str | etree.Element) -> str:
""" Override default to handle any `etree` elements still in the stash. """
if isinstance(text, etree.Element):
return self.md.serializer(text)
else:
return str(text) | Override default to handle any `etree` elements still in the stash. | stash_to_string | python | Python-Markdown/markdown | markdown/extensions/md_in_html.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/md_in_html.py | BSD-3-Clause |
def test(self, parent: etree.Element, block: str) -> bool:
"""
Ensure first two rows (column header and separator row) are valid table rows.
Keep border check and separator row do avoid repeating the work.
"""
is_table = False
rows = [row.strip(' ') for row in block.spli... |
Ensure first two rows (column header and separator row) are valid table rows.
Keep border check and separator row do avoid repeating the work.
| test | python | Python-Markdown/markdown | markdown/extensions/tables.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/tables.py | BSD-3-Clause |
def _split(self, row: str) -> list[str]:
""" split a row of text with some code into a list of cells. """
elements = []
pipes = []
tics = []
tic_points = []
tic_region = []
good_pipes = []
# Parse row
# Throw out \\, and \|
for m in self.R... | split a row of text with some code into a list of cells. | _split | python | Python-Markdown/markdown | markdown/extensions/tables.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/tables.py | BSD-3-Clause |
def extendMarkdown(self, md):
""" Add an instance of `TableProcessor` to `BlockParser`. """
if '|' not in md.ESCAPED_CHARS:
md.ESCAPED_CHARS.append('|')
processor = TableProcessor(md.parser, self.getConfigs())
md.parser.blockprocessors.register(processor, 'table', 75) | Add an instance of `TableProcessor` to `BlockParser`. | extendMarkdown | python | Python-Markdown/markdown | markdown/extensions/tables.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/tables.py | BSD-3-Clause |
def unique(id: str, ids: MutableSet[str]) -> str:
""" Ensure id is unique in set of ids. Append '_1', '_2'... if not """
while id in ids or not id:
m = IDCOUNT_RE.match(id)
if m:
id = '%s_%d' % (m.group(1), int(m.group(2))+1)
else:
id = '%s_%d' % (id, 1)
ids.a... | Ensure id is unique in set of ids. Append '_1', '_2'... if not | unique | python | Python-Markdown/markdown | markdown/extensions/toc.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/toc.py | BSD-3-Clause |
def stashedHTML2text(text: str, md: Markdown, strip_entities: bool = True) -> str:
""" Extract raw HTML from stash, reduce to plain text and swap with placeholder. """
def _html_sub(m: re.Match[str]) -> str:
""" Substitute raw html with plain text. """
try:
raw = md.htmlStash.rawHtml... | Extract raw HTML from stash, reduce to plain text and swap with placeholder. | stashedHTML2text | python | Python-Markdown/markdown | markdown/extensions/toc.py | https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/toc.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.