2012-11-19 17:55:28 +01:00
|
|
|
"""
|
|
|
|
Fenced Code Extension for Python Markdown
|
|
|
|
=========================================
|
|
|
|
|
|
|
|
This extension adds Fenced Code Blocks to Python-Markdown.
|
|
|
|
|
|
|
|
>>> import markdown
|
|
|
|
>>> text = '''
|
|
|
|
... A paragraph before a fenced code block:
|
|
|
|
...
|
|
|
|
... ~~~
|
|
|
|
... Fenced code block
|
|
|
|
... ~~~
|
|
|
|
... '''
|
|
|
|
>>> html = markdown.markdown(text, extensions=['fenced_code'])
|
|
|
|
>>> print html
|
|
|
|
<p>A paragraph before a fenced code block:</p>
|
|
|
|
<pre><code>Fenced code block
|
|
|
|
</code></pre>
|
|
|
|
|
|
|
|
Works with safe_mode also (we check this because we are using the HtmlStash):
|
|
|
|
|
|
|
|
>>> print markdown.markdown(text, extensions=['fenced_code'], safe_mode='replace')
|
|
|
|
<p>A paragraph before a fenced code block:</p>
|
|
|
|
<pre><code>Fenced code block
|
|
|
|
</code></pre>
|
|
|
|
|
|
|
|
Include tilde's in a code block and wrap with blank lines:
|
|
|
|
|
|
|
|
>>> text = '''
|
|
|
|
... ~~~~~~~~
|
|
|
|
...
|
|
|
|
... ~~~~
|
|
|
|
... ~~~~~~~~'''
|
|
|
|
>>> print markdown.markdown(text, extensions=['fenced_code'])
|
|
|
|
<pre><code>
|
|
|
|
~~~~
|
|
|
|
</code></pre>
|
|
|
|
|
2017-03-20 18:54:00 +01:00
|
|
|
Removes trailing whitespace from code blocks that cause horizontal scrolling
|
|
|
|
>>> import markdown
|
|
|
|
>>> text = '''
|
|
|
|
... A paragraph before a fenced code block:
|
|
|
|
...
|
|
|
|
... ~~~
|
|
|
|
... Fenced code block \t\t\t\t\t\t\t
|
|
|
|
... ~~~
|
|
|
|
... '''
|
|
|
|
>>> html = markdown.markdown(text, extensions=['fenced_code'])
|
|
|
|
>>> print html
|
|
|
|
<p>A paragraph before a fenced code block:</p>
|
|
|
|
<pre><code>Fenced code block
|
|
|
|
</code></pre>
|
|
|
|
|
2012-11-19 17:55:28 +01:00
|
|
|
Language tags:
|
|
|
|
|
|
|
|
>>> text = '''
|
|
|
|
... ~~~~{.python}
|
|
|
|
... # Some python code
|
|
|
|
... ~~~~'''
|
|
|
|
>>> print markdown.markdown(text, extensions=['fenced_code'])
|
|
|
|
<pre><code class="python"># Some python code
|
|
|
|
</code></pre>
|
|
|
|
|
|
|
|
Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).
|
|
|
|
|
|
|
|
Project website: <http://packages.python.org/Markdown/extensions/fenced_code_blocks.html>
|
|
|
|
Contact: markdown@freewisdom.org
|
|
|
|
|
|
|
|
License: BSD (see ../docs/LICENSE for details)
|
|
|
|
|
|
|
|
Dependencies:
|
|
|
|
* [Python 2.4+](http://python.org)
|
|
|
|
* [Markdown 2.0+](http://packages.python.org/Markdown/)
|
|
|
|
* [Pygments (optional)](http://pygments.org)
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
import re
|
|
|
|
import markdown
|
2017-03-20 16:56:39 +01:00
|
|
|
from django.utils.html import escape
|
2016-10-16 08:36:31 +02:00
|
|
|
from markdown.extensions.codehilite import CodeHilite, CodeHiliteExtension
|
2019-05-16 22:38:53 +02:00
|
|
|
from zerver.lib.exceptions import BugdownRenderingException
|
2017-03-20 16:56:39 +01:00
|
|
|
from zerver.lib.tex import render_tex
|
2019-05-16 22:38:53 +02:00
|
|
|
from typing import Any, Dict, Iterable, List, MutableSequence, Optional
|
2012-11-19 17:55:28 +01:00
|
|
|
|
|
|
|
# Global vars
|
2017-11-04 05:34:38 +01:00
|
|
|
FENCE_RE = re.compile("""
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
# ~~~ or ```
|
|
|
|
(?P<fence>
|
|
|
|
^(?:~{3,}|`{3,})
|
2012-11-19 17:55:28 +01:00
|
|
|
)
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
|
|
|
|
[ ]* # spaces
|
|
|
|
|
|
|
|
(
|
2016-06-16 13:24:52 +02:00
|
|
|
\\{?\\.?
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
(?P<lang>
|
2017-06-15 23:39:20 +02:00
|
|
|
[a-zA-Z0-9_+-./#]*
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
) # "py" or "javascript"
|
2016-06-16 13:24:52 +02:00
|
|
|
\\}?
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
) # language, like ".py" or "{javascript}"
|
2014-03-06 00:05:49 +01:00
|
|
|
[ ]* # spaces
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
$
|
|
|
|
""", re.VERBOSE)
|
|
|
|
|
|
|
|
|
2017-11-03 03:12:25 +01:00
|
|
|
CODE_WRAP = '<pre><code%s>%s\n</code></pre>'
|
|
|
|
LANG_TAG = ' class="%s"'
|
2012-11-19 17:55:28 +01:00
|
|
|
|
2019-05-16 22:38:53 +02:00
|
|
|
def validate_curl_content(lines: List[str]) -> None:
|
|
|
|
error_msg = """
|
|
|
|
Missing required -X argument in curl command:
|
|
|
|
|
|
|
|
{command}
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
for line in lines:
|
2019-08-07 10:55:41 +02:00
|
|
|
regex = r'curl [-](sS)?X "?(GET|DELETE|PATCH|POST)"?'
|
2019-05-16 22:38:53 +02:00
|
|
|
if line.startswith('curl'):
|
|
|
|
if re.search(regex, line) is None:
|
|
|
|
raise BugdownRenderingException(error_msg.format(command=line.strip()))
|
|
|
|
|
|
|
|
|
|
|
|
CODE_VALIDATORS = {
|
|
|
|
'curl': validate_curl_content,
|
|
|
|
}
|
|
|
|
|
2012-11-19 17:55:28 +01:00
|
|
|
class FencedCodeExtension(markdown.Extension):
|
2019-05-16 22:38:53 +02:00
|
|
|
def __init__(self, config: Optional[Dict[str, Any]]=None) -> None:
|
|
|
|
if config is None:
|
|
|
|
config = {}
|
|
|
|
self.config = {
|
|
|
|
'run_content_validators': [
|
|
|
|
config.get('run_content_validators', False),
|
|
|
|
'Boolean specifying whether to run content validation code in CodeHandler'
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
for key, value in config.items():
|
|
|
|
self.setConfig(key, value)
|
2012-11-19 17:55:28 +01:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def extendMarkdown(self, md: markdown.Markdown, md_globals: Dict[str, Any]) -> None:
|
2012-11-19 17:55:28 +01:00
|
|
|
""" Add FencedBlockPreprocessor to the Markdown instance. """
|
|
|
|
md.registerExtension(self)
|
2019-05-16 22:38:53 +02:00
|
|
|
processor = FencedBlockPreprocessor(
|
|
|
|
md, run_content_validators=self.config['run_content_validators'][0])
|
|
|
|
md.preprocessors.register(processor, 'fenced_code_block', 25)
|
2012-11-19 17:55:28 +01:00
|
|
|
|
|
|
|
|
2018-11-02 17:11:42 +01:00
|
|
|
class BaseHandler:
|
|
|
|
def handle_line(self, line: str) -> None:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def done(self) -> None:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2019-05-16 22:38:53 +02:00
|
|
|
def generic_handler(processor: Any, output: MutableSequence[str],
|
|
|
|
fence: str, lang: str,
|
|
|
|
run_content_validators: Optional[bool]=False) -> BaseHandler:
|
2018-11-02 17:11:42 +01:00
|
|
|
if lang in ('quote', 'quoted'):
|
|
|
|
return QuoteHandler(processor, output, fence)
|
|
|
|
elif lang in ('math', 'tex', 'latex'):
|
|
|
|
return TexHandler(processor, output, fence)
|
|
|
|
else:
|
2019-05-16 22:38:53 +02:00
|
|
|
return CodeHandler(processor, output, fence, lang, run_content_validators)
|
2018-11-02 17:11:42 +01:00
|
|
|
|
2019-05-16 22:38:53 +02:00
|
|
|
def check_for_new_fence(processor: Any, output: MutableSequence[str], line: str,
|
|
|
|
run_content_validators: Optional[bool]=False) -> None:
|
2018-11-02 17:11:42 +01:00
|
|
|
m = FENCE_RE.match(line)
|
|
|
|
if m:
|
|
|
|
fence = m.group('fence')
|
|
|
|
lang = m.group('lang')
|
2019-05-16 22:38:53 +02:00
|
|
|
|
|
|
|
handler = generic_handler(processor, output, fence, lang, run_content_validators)
|
2018-11-02 17:11:42 +01:00
|
|
|
processor.push(handler)
|
|
|
|
else:
|
|
|
|
output.append(line)
|
|
|
|
|
|
|
|
class OuterHandler(BaseHandler):
|
2019-05-16 22:38:53 +02:00
|
|
|
def __init__(self, processor: Any, output: MutableSequence[str],
|
|
|
|
run_content_validators: Optional[bool]=False) -> None:
|
2018-11-02 17:11:42 +01:00
|
|
|
self.output = output
|
|
|
|
self.processor = processor
|
2019-05-16 22:38:53 +02:00
|
|
|
self.run_content_validators = run_content_validators
|
2018-11-02 17:11:42 +01:00
|
|
|
|
|
|
|
def handle_line(self, line: str) -> None:
|
2019-05-16 22:38:53 +02:00
|
|
|
check_for_new_fence(self.processor, self.output, line,
|
|
|
|
self.run_content_validators)
|
2018-11-02 17:11:42 +01:00
|
|
|
|
|
|
|
def done(self) -> None:
|
|
|
|
self.processor.pop()
|
|
|
|
|
|
|
|
class CodeHandler(BaseHandler):
|
2019-05-16 22:38:53 +02:00
|
|
|
def __init__(self, processor: Any, output: MutableSequence[str],
|
|
|
|
fence: str, lang: str, run_content_validators: Optional[bool]=False) -> None:
|
2018-11-02 17:11:42 +01:00
|
|
|
self.processor = processor
|
|
|
|
self.output = output
|
|
|
|
self.fence = fence
|
|
|
|
self.lang = lang
|
|
|
|
self.lines = [] # type: List[str]
|
2019-05-16 22:38:53 +02:00
|
|
|
self.run_content_validators = run_content_validators
|
2018-11-02 17:11:42 +01:00
|
|
|
|
|
|
|
def handle_line(self, line: str) -> None:
|
|
|
|
if line.rstrip() == self.fence:
|
|
|
|
self.done()
|
|
|
|
else:
|
|
|
|
self.lines.append(line.rstrip())
|
|
|
|
|
|
|
|
def done(self) -> None:
|
|
|
|
text = '\n'.join(self.lines)
|
2019-05-16 22:38:53 +02:00
|
|
|
|
|
|
|
# run content validators (if any)
|
|
|
|
if self.run_content_validators:
|
|
|
|
validator = CODE_VALIDATORS.get(self.lang, lambda text: None)
|
|
|
|
validator(self.lines)
|
|
|
|
|
2018-11-02 17:11:42 +01:00
|
|
|
text = self.processor.format_code(self.lang, text)
|
|
|
|
text = self.processor.placeholder(text)
|
|
|
|
processed_lines = text.split('\n')
|
|
|
|
self.output.append('')
|
|
|
|
self.output.extend(processed_lines)
|
|
|
|
self.output.append('')
|
|
|
|
self.processor.pop()
|
|
|
|
|
|
|
|
class QuoteHandler(BaseHandler):
|
|
|
|
def __init__(self, processor: Any, output: MutableSequence[str], fence: str) -> None:
|
|
|
|
self.processor = processor
|
|
|
|
self.output = output
|
|
|
|
self.fence = fence
|
|
|
|
self.lines = [] # type: List[str]
|
|
|
|
|
|
|
|
def handle_line(self, line: str) -> None:
|
|
|
|
if line.rstrip() == self.fence:
|
|
|
|
self.done()
|
|
|
|
else:
|
|
|
|
check_for_new_fence(self.processor, self.lines, line)
|
|
|
|
|
|
|
|
def done(self) -> None:
|
|
|
|
text = '\n'.join(self.lines)
|
|
|
|
text = self.processor.format_quote(text)
|
|
|
|
processed_lines = text.split('\n')
|
|
|
|
self.output.append('')
|
|
|
|
self.output.extend(processed_lines)
|
|
|
|
self.output.append('')
|
|
|
|
self.processor.pop()
|
|
|
|
|
|
|
|
class TexHandler(BaseHandler):
|
|
|
|
def __init__(self, processor: Any, output: MutableSequence[str], fence: str) -> None:
|
|
|
|
self.processor = processor
|
|
|
|
self.output = output
|
|
|
|
self.fence = fence
|
|
|
|
self.lines = [] # type: List[str]
|
|
|
|
|
|
|
|
def handle_line(self, line: str) -> None:
|
|
|
|
if line.rstrip() == self.fence:
|
|
|
|
self.done()
|
|
|
|
else:
|
|
|
|
self.lines.append(line)
|
|
|
|
|
|
|
|
def done(self) -> None:
|
|
|
|
text = '\n'.join(self.lines)
|
|
|
|
text = self.processor.format_tex(text)
|
|
|
|
text = self.processor.placeholder(text)
|
|
|
|
processed_lines = text.split('\n')
|
|
|
|
self.output.append('')
|
|
|
|
self.output.extend(processed_lines)
|
|
|
|
self.output.append('')
|
|
|
|
self.processor.pop()
|
|
|
|
|
|
|
|
|
2012-11-19 17:55:28 +01:00
|
|
|
class FencedBlockPreprocessor(markdown.preprocessors.Preprocessor):
|
2019-05-16 22:38:53 +02:00
|
|
|
def __init__(self, md: markdown.Markdown, run_content_validators: Optional[bool]=False) -> None:
|
2012-11-19 17:55:28 +01:00
|
|
|
markdown.preprocessors.Preprocessor.__init__(self, md)
|
|
|
|
|
|
|
|
self.checked_for_codehilite = False
|
2019-05-16 22:38:53 +02:00
|
|
|
self.run_content_validators = run_content_validators
|
2017-05-07 17:01:30 +02:00
|
|
|
self.codehilite_conf = {} # type: Dict[str, List[Any]]
|
2012-11-19 17:55:28 +01:00
|
|
|
|
2018-11-02 17:11:42 +01:00
|
|
|
def push(self, handler: BaseHandler) -> None:
|
|
|
|
self.handlers.append(handler)
|
|
|
|
|
|
|
|
def pop(self) -> None:
|
|
|
|
self.handlers.pop()
|
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def run(self, lines: Iterable[str]) -> List[str]:
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
""" Match and store Fenced Code Blocks in the HtmlStash. """
|
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
output = [] # type: List[str]
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
|
|
|
|
processor = self
|
2018-11-02 17:11:42 +01:00
|
|
|
self.handlers = [] # type: List[BaseHandler]
|
|
|
|
|
2019-05-16 22:38:53 +02:00
|
|
|
handler = OuterHandler(processor, output, self.run_content_validators)
|
2018-11-02 17:11:42 +01:00
|
|
|
self.push(handler)
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
|
|
|
|
for line in lines:
|
2018-11-02 17:11:42 +01:00
|
|
|
self.handlers[-1].handle_line(line)
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
|
2018-11-02 17:11:42 +01:00
|
|
|
while self.handlers:
|
|
|
|
self.handlers[-1].done()
|
Support arbitrarily nested fenced quote/code blocks.
Now we can nest fenced code/quote blocks inside of quote
blocks down to arbitrary depths. Code blocks are always leafs.
Fenced blocks start with at least three tildes or backticks,
and the clump of punctuation then becomes the terminator for
the block. If the user ends their message without terminators,
all blocks are automatically closed.
When inside a quote block, you can start another fenced block
with any header that doesn't match the end-string of the outer
block. (If you don't want to specify a language, then you
can change the number of backticks/tildes to avoid amiguity.)
Most of the heavy lifting happens in FencedBlockPreprocessor.run().
The parser works by pushing handlers on to a stack and popping
them off when the ends of blocks are encountered. Parents communicate
with their children by passing in a simple Python list of strings
for the child to append to. Handlers also maintain their own
lists for their own content, and when their done() method is called,
they render their data as needed.
The handlers are objects returned by functions, and the handler
functions close on variables push, pop, and processor. The closure
style here makes the handlers pretty tightly coupled to the outer
run() method. If we wanted to move to a class-based style, the
tradeoff would be that the class instances would have to marshall
push/pop/processor etc., but we could test the components more
easily in isolation.
Dealing with blank lines is very fiddly inside of bugdown.
The new functionality here is captured in the test
BugdownTest.test_complexly_nested_quote().
(imported from commit 53886c8de74bdf2bbd3cef8be9de25f05bddb93c)
2013-11-20 23:25:48 +01:00
|
|
|
|
|
|
|
# This fiddly handling of new lines at the end of our output was done to make
|
|
|
|
# existing tests pass. Bugdown is just kind of funny when it comes to new lines,
|
|
|
|
# but we could probably remove this hack.
|
|
|
|
if len(output) > 2 and output[-2] != '':
|
|
|
|
output.append('')
|
|
|
|
return output
|
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def format_code(self, lang: str, text: str) -> str:
|
2013-11-20 19:48:44 +01:00
|
|
|
if lang:
|
|
|
|
langclass = LANG_TAG % (lang,)
|
2016-06-16 13:24:52 +02:00
|
|
|
else:
|
|
|
|
langclass = ''
|
2013-11-20 19:48:44 +01:00
|
|
|
|
2013-11-20 19:11:07 +01:00
|
|
|
# Check for code hilite extension
|
|
|
|
if not self.checked_for_codehilite:
|
|
|
|
for ext in self.markdown.registeredExtensions:
|
|
|
|
if isinstance(ext, CodeHiliteExtension):
|
|
|
|
self.codehilite_conf = ext.config
|
|
|
|
break
|
|
|
|
|
|
|
|
self.checked_for_codehilite = True
|
|
|
|
|
|
|
|
# If config is not empty, then the codehighlite extension
|
|
|
|
# is enabled, so we call it to highlite the code
|
|
|
|
if self.codehilite_conf:
|
|
|
|
highliter = CodeHilite(text,
|
2016-12-11 14:30:45 +01:00
|
|
|
linenums=self.codehilite_conf['linenums'][0],
|
|
|
|
guess_lang=self.codehilite_conf['guess_lang'][0],
|
|
|
|
css_class=self.codehilite_conf['css_class'][0],
|
|
|
|
style=self.codehilite_conf['pygments_style'][0],
|
|
|
|
use_pygments=self.codehilite_conf['use_pygments'][0],
|
|
|
|
lang=(lang or None),
|
|
|
|
noclasses=self.codehilite_conf['noclasses'][0])
|
2013-11-20 19:11:07 +01:00
|
|
|
|
|
|
|
code = highliter.hilite()
|
|
|
|
else:
|
|
|
|
code = CODE_WRAP % (langclass, self._escape(text))
|
|
|
|
|
|
|
|
return code
|
2013-01-29 16:14:30 +01:00
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def format_quote(self, text: str) -> str:
|
2013-11-20 19:29:54 +01:00
|
|
|
paragraphs = text.split("\n\n")
|
|
|
|
quoted_paragraphs = []
|
|
|
|
for paragraph in paragraphs:
|
|
|
|
lines = paragraph.split("\n")
|
|
|
|
quoted_paragraphs.append("\n".join("> " + line for line in lines if line != ''))
|
|
|
|
return "\n\n".join(quoted_paragraphs)
|
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def format_tex(self, text: str) -> str:
|
2017-03-20 16:56:39 +01:00
|
|
|
paragraphs = text.split("\n\n")
|
|
|
|
tex_paragraphs = []
|
|
|
|
for paragraph in paragraphs:
|
|
|
|
html = render_tex(paragraph, is_inline=False)
|
|
|
|
if html is not None:
|
|
|
|
tex_paragraphs.append(html)
|
|
|
|
else:
|
|
|
|
tex_paragraphs.append('<span class="tex-error">' +
|
|
|
|
escape(paragraph) + '</span>')
|
|
|
|
return "\n\n".join(tex_paragraphs)
|
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def placeholder(self, code: str) -> str:
|
2018-12-20 08:28:40 +01:00
|
|
|
return self.markdown.htmlStash.store(code)
|
2013-11-20 21:03:57 +01:00
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def _escape(self, txt: str) -> str:
|
2012-11-19 17:55:28 +01:00
|
|
|
""" basic html escaping """
|
|
|
|
txt = txt.replace('&', '&')
|
|
|
|
txt = txt.replace('<', '<')
|
|
|
|
txt = txt.replace('>', '>')
|
|
|
|
txt = txt.replace('"', '"')
|
|
|
|
return txt
|
|
|
|
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def makeExtension(*args: Any, **kwargs: None) -> FencedCodeExtension:
|
2019-05-16 22:38:53 +02:00
|
|
|
return FencedCodeExtension(kwargs)
|
2012-11-19 17:55:28 +01:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
doctest.testmod()
|