File: tilde.py

package info (click to toggle)
pymdown-extensions 10.13-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 7,072 kB
  • sloc: python: 60,116; javascript: 846; sh: 8; makefile: 5
file content (185 lines) | stat: -rwxr-xr-x 7,333 bytes parent folder | download | duplicates (2)
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
Tilde.

pymdownx.tilde
Really simple plugin to add support for
`<del>test</del>` tags as `~~test~~` and
`<sub>test</sub>` tags as `~test~`

MIT license.

Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import re
from markdown import Extension
from markdown.inlinepatterns import SimpleTextInlineProcessor
from . import util

SMART_CONTENT = r'(.+?~*?)'
SMART_LIMITED_CONTENT = r'((?:[^~]|(?<=\w)~+?(?=\w)|(?<=\s)~+?(?=\s))+?)'
CONTENT = r'(~|[^\s]+?)'
CONTENT2 = r'((?:[^~]|(?<!~{2})~)+?)'

# Avoid starting a pattern with tilde tokens that are surrounded by white space.
NOT_TILDE = r'((^|(?<=\s))(~+)(?=\s|$))'

# `~~~del,sub~~~`
DEL_SUB = r'(~{3})(?!\s)(~{1,2}|[^~\s]+?)(?<!\s)\1'
# `~~~del,sub~del~~`
DEL_SUB2 = r'(~{{3}})(?![\s~]){}(?<!\s)~{}(?<!\s)~{{2}}'.format(CONTENT, CONTENT2)
# `~~~sub,del~~sub~`
SUB_DEL = r'(~{{3}})(?![\s~]){}(?<!\s)~{{2}}{}(?<!\s)~'.format(CONTENT, CONTENT)
# `~~del~sub,del~~~`
DEL_SUB3 = r'(~{{2}})(?![\s~]){}~(?![\s~]){}(?<!\s)~{{3}}'.format(CONTENT2, CONTENT)
# `~~del~~`
DEL = r'(~{{2}})(?!\s){}(?<!\s)\1'.format(CONTENT2)
# `~sub~`
SUB = r'(~)(?!\s){}(?<!\s)\1'.format(CONTENT)
# `~sub ~~sub,del~~~`
SUB_DEL2 = r'(?<!~)(~)(?![~\s]){}~{{2}}{}~{{3}}'.format(CONTENT, CONTENT)
# Prioritize ~value~ when ~~value~~ is nested within
SUB2 = r'(?<!~)(~)(?![~\s])((?:[^\s~]|~{2,})+?)(?<![~\s])(~)(?!~)'

# Smart rules for when "smart tilde" is enabled
# SMART: `~~~del,sub~~~`
SMART_DEL_SUB = r'(~{{3}})(?![\s~]){}(?<!\s)\1'.format(CONTENT)
# SMART: `~~~del,sub~ del~~`
SMART_DEL_SUB2 = \
    r'(~{{3}})(?![\s~]){}(?<!\s)~(?:(?=_)|(?![\w~])){}(?<!\s)~{{2}}'.format(
        CONTENT, SMART_LIMITED_CONTENT
    )
# SMART: `~~~sub,del~~ sub~`
SMART_SUB_DEL = \
    r'(~{{3}})(?![\s~]){}(?<!\s)~{{2}}(?:(?=_)|(?![\w~])){}(?<!\s)~'.format(
        CONTENT, CONTENT
    )
# SMART: `~~del~~`
SMART_DEL = r'(?:(?<=_)|(?<![\w~]))(~{{2}})(?![\s~]){}(?<!\s)\1(?:(?=_)|(?![\w~]))'.format(SMART_CONTENT)
# SMART: `~sub ~~sub,del~~~`
SMART_SUB_DEL2 = \
    r'(?<!~)(~)(?![\s~]){}(?:(?<=_)|(?<![\w~]))~{{2}}(?![\s~]){}(?<!\s)~{{3}}'.format(
        CONTENT, CONTENT
    )
# SMART: `~sub ~~sub,del~~~`
SMART_DEL_SUB3 = \
    r'(?<!~)(~{{2}})(?![\s~]){}(?:(?<=_)|(?<![\w~]))~(?![\s~]){}(?<!\s)~{{3}}'.format(
        SMART_LIMITED_CONTENT, CONTENT
    )


class TildeProcessor(util.PatternSequenceProcessor):
    """Emphasis processor for handling delete and subscript matches."""

    PATTERNS = [
        util.PatSeqItem(re.compile(DEL_SUB, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
        util.PatSeqItem(re.compile(SUB_DEL, re.DOTALL | re.UNICODE), 'double', 'sub,del'),
        util.PatSeqItem(re.compile(DEL_SUB2, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
        util.PatSeqItem(re.compile(DEL_SUB3, re.DOTALL | re.UNICODE), 'double2', 'del,sub'),
        util.PatSeqItem(re.compile(DEL, re.DOTALL | re.UNICODE), 'single', 'del'),
        util.PatSeqItem(re.compile(SUB_DEL2, re.DOTALL | re.UNICODE), 'double2', 'sub,del'),
        util.PatSeqItem(re.compile(SUB2, re.DOTALL | re.UNICODE), 'single', 'sub', True),
        util.PatSeqItem(re.compile(SUB, re.DOTALL | re.UNICODE), 'single', 'sub')
    ]


class TildeSmartProcessor(util.PatternSequenceProcessor):
    """Smart delete and subscript processor."""

    PATTERNS = [
        util.PatSeqItem(re.compile(SMART_DEL_SUB, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
        util.PatSeqItem(re.compile(SMART_SUB_DEL, re.DOTALL | re.UNICODE), 'double', 'sub,del'),
        util.PatSeqItem(re.compile(SMART_DEL_SUB2, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
        util.PatSeqItem(re.compile(SMART_DEL_SUB3, re.DOTALL | re.UNICODE), 'double2', 'del,sub'),
        util.PatSeqItem(re.compile(SMART_DEL, re.DOTALL | re.UNICODE), 'single', 'del'),
        util.PatSeqItem(re.compile(SMART_SUB_DEL2, re.DOTALL | re.UNICODE), 'double2', 'sub,del'),
        util.PatSeqItem(re.compile(SUB2, re.DOTALL | re.UNICODE), 'single', 'sub', True),
        util.PatSeqItem(re.compile(SUB, re.DOTALL | re.UNICODE), 'single', 'sub')
    ]


class TildeSubProcessor(util.PatternSequenceProcessor):
    """Just subscript processor."""

    PATTERNS = [
        util.PatSeqItem(re.compile(SUB, re.DOTALL | re.UNICODE), 'single', 'sub')
    ]


class TildeDeleteProcessor(util.PatternSequenceProcessor):
    """Just delete processor."""

    PATTERNS = [
        util.PatSeqItem(re.compile(DEL, re.DOTALL | re.UNICODE), 'single', 'del')
    ]


class TildeSmartDeleteProcessor(util.PatternSequenceProcessor):
    """Just smart delete processor."""

    PATTERNS = [
        util.PatSeqItem(re.compile(SMART_DEL, re.DOTALL | re.UNICODE), 'single', 'del')
    ]


class DeleteSubExtension(Extension):
    """Add delete and/or subscript extension to Markdown class."""

    def __init__(self, *args, **kwargs):
        """Initialize."""

        self.config = {
            'smart_delete': [True, "Treat ~~connected~~words~~ intelligently - Default: True"],
            'delete': [True, "Enable delete - Default: True"],
            'subscript': [True, "Enable subscript - Default: True"]
        }

        super().__init__(*args, **kwargs)

    def extendMarkdown(self, md):
        """Insert `<del>test</del>` tags as `~~test~~` and `<sub>test</sub>` tags as `~test~`."""

        config = self.getConfigs()
        delete = bool(config.get('delete', True))
        subscript = bool(config.get('subscript', True))
        smart = bool(config.get('smart_delete', True))

        md.registerExtension(self)

        escape_chars = []
        if delete or subscript:
            escape_chars.append('~')
        if subscript:
            escape_chars.append(' ')
        util.escape_chars(md, escape_chars)

        tilde = None
        md.inlinePatterns.register(SimpleTextInlineProcessor(NOT_TILDE), 'not_tilde', 70)
        if delete and subscript:
            tilde = TildeSmartProcessor(r'~') if smart else TildeProcessor(r'~')
        elif delete:
            tilde = TildeSmartDeleteProcessor(r'~') if smart else TildeDeleteProcessor(r'~')
        elif subscript:
            tilde = TildeSubProcessor(r'~')

        if tilde is not None:
            md.inlinePatterns.register(tilde, "sub_del", 65)


def makeExtension(*args, **kwargs):
    """Return extension."""

    return DeleteSubExtension(*args, **kwargs)