diff options
author | rsiddharth <s@ricketyspace.net> | 2017-07-24 00:40:01 +0000 |
---|---|---|
committer | rsiddharth <s@ricketyspace.net> | 2017-07-24 00:40:01 +0000 |
commit | b5bc0fc9cbe3df899a12ec1bfe90bd8fa21ddd74 (patch) | |
tree | 87223c1645ba9c9f4c40a61ce152a79a57dd4af7 /md_tw.py | |
parent | 40861fcbc949bf1f1835399f76e096192bccb319 (diff) |
md_tw.py: Add Text Wrap classes (derived from mistune' classes).
* md_tw.py (TWBlockLexer, TWInlineLexer, TWRenderer)
(TWMarkdown): New classes.
* tests/data/paragraphs-with-inline-wrapped.md: New file.
* tests/data/paragraphs-with-inline.md: New file.
* tests/data/paragraphs-wrapped.md: New file.
* tests/data/paragraphs.md: New file.
* tests/test_md_tw.py (TestTWBlockLexer, TestTWInlineLexer,
TestTWRenderer, TestTWMarkdown)
(TestTextWrapParagraphs): New test classes.
Diffstat (limited to 'md_tw.py')
-rw-r--r-- | md_tw.py | 91 |
1 files changed, 91 insertions, 0 deletions
@@ -18,5 +18,96 @@ # along with markdown-textwrap (see COPYING). If not, see # <http://www.gnu.org/licenses/>. +import textwrap + +from mistune import BlockLexer, InlineLexer, Renderer, Markdown + + +class TWBlockLexer(BlockLexer): + """Text Wrap Block level lexer for block grammars.""" + + def __init__(self, rules=None, **kwargs): + super(TWBlockLexer, self).__init__(rules, **kwargs) + + self.default_rules = ['paragraph', 'text'] + + +class TWInlineLexer(InlineLexer): + """Text Wrap Inline level lexer for inline gramars.""" + + def __init__(self, renderer, rules=None, **kwargs): + super(TWInlineLexer, self).__init__(renderer, rules, **kwargs) + + # No inline rules. + self.default_rules = [] + + def output(self, text, rules=None): + # Don't parse inline text. + return text + + +class TWRenderer(Renderer): + """Text Wrap Renderer.""" + + def __init__(self, **kwargs): + super(TWRenderer, self).__init__(**kwargs) + + # Initalize textwrap.TextWrapper class + self.tw = textwrap.TextWrapper( + width=kwargs.get('tw_width', 72) + ) + + + def _tw_set_options(self, **kwargs): + """ + Set options for the local textwrap.TextWrapper instance. + """ + # Recognized options. + opts = [ + 'width', + 'initial_indent', + 'subsequent_indent', + 'drop_whitespace' + ] + + for opt, val in kwargs.items(): + if not opt in opts: + continue + + # Set option + setattr(self.tw, opt, val) + + + def _tw_fill(self, text, **kwargs): + """Wrap text. + """ + self._tw_set_options(**kwargs) + return self.tw.fill(text) + + + def paragraph(self, text): + return '\n{}\n'.format(self._tw_fill(text)) + + +class TWMarkdown(Markdown): + """Text Wrap Markdown parser. + """ + + def __init__(self, **kwargs): + renderer = TWRenderer(**kwargs) + + super(TWMarkdown, self).__init__( + renderer, + TWInlineLexer, + TWBlockLexer + ) + + def parse(self, text): + out = super(TWMarkdown, self).parse(text) + + # Strip newline at the beginning. + return out.lstrip('\n') + + def main(): print('USAGE: md_tw 72 file.md file2.md [...]') |