aboutsummaryrefslogtreecommitdiff
path: root/_ext/gemtext_builder.py
blob: c26b0531109990c197ed103144c12888861f2272 (plain)
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
from pathlib import Path
from typing import Set

from docutils import nodes, writers
from docutils.io import StringOutput
from sphinx.builders import Builder
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
from sphinx.util.osutil import ensuredir, os_path

logger = logging.getLogger(__name__)

class GemtextWriter(writers.Writer):
    def __init__(self, builder):
        super().__init__()
        self.builder = builder
    
    def translate(self):
        visitor = self.builder.create_translator(self.document, self.builder)
        self.document.walkabout(visitor)
        self.output = '\n'.join(visitor.body) + '\n'

class GemtextTranslator(SphinxTranslator):
    def __init__(self, document: nodes.document, builder):
        super().__init__(document, builder)
        self.heading_level = 0
        self.current_line = ''
        self.body = []
        self.literal = False
        self.pending_links = []

    def _finish_line(self):
        if self.current_line != '':
            self.body.append(self.current_line)
            self.current_line = ''
    
    def visit_document(self, node: nodes.document):
        self.heading_level = 1
        self.current_line = ''
        self.body = []
        self.literal = False
        self.pending_links = []
    
    def depart_document(self, node: nodes.document):
        self._finish_line()
    
    def visit_section(self, node: nodes.section):
        self.heading_level += 1
        if len(self.body) > 0 and self.body[-1] != '':
            self.body.append('')
    
    def depart_section(self, node: nodes.section):
        self.heading_level -= 1
    
    def visit_title(self, node: nodes.title):
        pass

    def depart_title(self, node: nodes.title):
        self.current_line = '#' * (self.heading_level - 1) + ' ' + self.current_line
        self._finish_line()
        self.body.append('')

    def visit_Text(self, node: nodes.Text):
        text = node.astext()
        if not self.literal:
            text = text.replace('\n', ' ')
        self.current_line += text
    
    def depart_Text(self, node: nodes.Text):
        pass

    def visit_paragraph(self, node: nodes.paragraph):
        pass

    def depart_paragraph(self, node: nodes.paragraph):
        self._finish_line()
        self.body += self.pending_links
        self.pending_links = []
        self.body.append('')

    def visit_reference(self, node: nodes.reference):
        pass

    def depart_reference(self, node: nodes.reference):
        if 'refuri' not in node.attributes:
            return
        if self.current_line.startswith('=>'):
            self._finish_line()
            self.body.append('=> {} {}'.format(node.attributes['refuri'], node.astext()))
        else:
            self.pending_links.append('=> {} {}'.format(node.attributes['refuri'], node.astext()))

    def visit_image(self, node: nodes.image):
        if self.current_line == '':
            self.body.append('=> {} {}'.format(node.attributes['uri'], node.attributes['alt']))
        else:
            raise NotImplementedError('inline images')
    
    def depart_image(self, node: nodes.image):
        pass

    def visit_comment(self, node: nodes.comment):
        raise nodes.SkipNode

    def visit_strong(self, node: nodes.strong):
        self.current_line += '**'
    
    depart_strong = visit_strong

    def visit_emphasis(self, node: nodes.emphasis):
        self.current_line += '_'
    
    depart_emphasis = visit_emphasis

    def visit_target(self, node: nodes.target):
        raise nodes.SkipNode

    def visit_bullet_list(self, node: nodes.bullet_list):
        pass

    def depart_bullet_list(self, node: nodes.bullet_list):
        if self.body[-1] != '':
            self.body.append('')

    def visit_list_item(self, node: nodes.list_item):
        self.current_line += '* '

    def depart_list_item(self, node: nodes.list_item):
        if self.body[-1] == '':
            self.body = self.body[:-1]
        if self.body[-1].startswith('=>') and self.body[-1].endswith(self.body[-2].replace('* ', '')):
            self.body = self.body[:-2] + [self.body[-1]]

    def visit_compound(self, node: nodes.compound):
        pass

    def depart_compound(self, node: nodes.compound):
        pass

    def visit_inline(self, node: nodes.inline):
        pass

    def depart_inline(self, node: nodes.inline):
        pass

    def visit_title_reference(self, node: nodes.title_reference):
        pass

    def depart_title_reference(self, node: nodes.title_reference):
        pass

    def visit_literal(self, node: nodes.literal):
        self.current_line += '`'

    depart_literal = visit_literal

    def visit_literal_block(self, node: nodes.literal_block):
        if self.body[-1] != '':
            self.body.append('')
        self.body.append('```')
        self.literal = True

    def depart_literal_block(self, node: nodes.literal_block):
        self._finish_line()
        self.body.append('```')
        self.body.append('')
        self.literal = False
    
    def visit_index(self, node: nodes.Node):
        pass
    
    def depart_index(self, node: nodes.Node):
        pass

    def visit_desc(self, node: nodes.Node):
        pass
    
    def depart_desc(self, node: nodes.Node):
        pass

    visit_term = visit_list_item

    def depart_term(self, node: nodes.Node):
        self._finish_line()

    def visit_definition(self, node: nodes.Node):
        pass

    def depart_definition(self, node: nodes.Node):
        pass

    visit_desc_signature = visit_term
    depart_desc_signature = depart_term

    def visit_desc_name(self, node: nodes.Node):
        pass

    def depart_desc_name(self, node: nodes.Node):
        pass

    def visit_desc_content(self, node: nodes.Node):
        pass

    def depart_desc_content(self, node: nodes.Node):
        pass

    def visit_glossary(self, node: nodes.Node):
        pass

    def depart_glossary(self, node: nodes.Node):
        pass

    def visit_definition_list(self, node: nodes.Node):
        pass

    def depart_definition_list(self, node: nodes.Node):
        pass

    def visit_definition_list_item(self, node: nodes.Node):
        pass

    def depart_definition_list_item(self, node: nodes.Node):
        pass

    def visit_todo_node(self, node: nodes.Node):
        pass

    def depart_todo_node(self, node: nodes.Node):
        pass

    def visit_note(self, node: nodes.Node):
        pass

    def depart_note(self, node: nodes.Node):
        pass

    def visit_math(self, node: nodes.Node):
        pass

    def depart_math(self, node: nodes.Node):
        pass

class GemtextBuilder(Builder):
    name = 'gmi'
    format = 'gmi'

    out_suffix = '.gmi'
    default_translator_class = GemtextTranslator

    def get_outdated_docs(self):
        yield from self.env.found_docs # can't be fucked to implement this right
        yield 'genindex'
    
    def get_target_uri(self, docname: str, typ: str = None):
        return docname + '.gmi'
    
    def prepare_writing(self, docnames: Set[str]):
        self.writer = GemtextWriter(self)

    def write_doc(self, docname: str, doctree: nodes.document):
        destination = StringOutput(encoding='utf-8')
        self.writer.write(doctree, destination)
        out_name = Path(self.outdir, os_path(docname) + '.gmi')
        out_name.parent.mkdir(parents=True, exist_ok=True)
        with open(out_name, 'w', encoding='utf-8') as out_file:
            out_file.write(self.writer.output)

def setup(app):
    app.add_builder(GemtextBuilder)

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }