summaryrefslogtreecommitdiffstats
path: root/md_tw.py
blob: 238cbb2eedcd8562fd276430249d1d37904de489 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# -*- coding: utf-8 -*-
#
#   Copyright © 2017 markdown-textwrap contributors.
#
#    This file is part of markdown-textwrap.
#
#   markdown-textwrap is free software: you can redistribute it
#   and/or modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation, either version 3 of
#   the License, or (at your option) any later version.
#
#   markdown-textwrap is distributed in the hope that it will be
#   useful, but WITHOUT ANY WARRANTY; without even the implied
#   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#   See the GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with markdown-textwrap (see COPYING).  If not, see
#   <http://www.gnu.org/licenses/>.

import re
import textwrap

import mistune


class TWBlockLexer(mistune.BlockLexer):
    """Text Wrap Block lexer for block grammar."""

    def __init__(self, rules=None, **kwargs):
        super(TWBlockLexer, self).__init__(rules, **kwargs)

        # from mistune
        self._key_pattern = re.compile(r'\s+')

    # from mistune
    def _keyify(self, key):
        key = mistune.escape(key.lower(), quote=True)
        return self._key_pattern.sub(' ', key)

    def parse_block_code(self, m):
        self.tokens.append({
            'type': 'code',
            'lang': None,
            'text': m.group(0),
        })

    def parse_fences(self, m):
        self.tokens.append({
            'type': 'code',
            'lang': None,
            'text': m.group(0),
        })

    def parse_heading(self, m):
        self.tokens.append({
            'type': 'heading',
            'level': len(m.group(1)),
            'text': m.group(0),
        })

    def parse_lheading(self, m):
        """Parse setext heading."""
        self.tokens.append({
            'type': 'heading',
            'level': 1 if m.group(2) == '=' else 2,
            'text': m.group(0),
        })

    def parse_hrule(self, m):
        self.tokens.append({
            'type': 'hrule',
            'text': m.group(0)
            })


class TWInlineLexer(mistune.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(mistune.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(mistune.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 [...]')