mdit-py-i18n 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.1
2
+ Name: mdit-py-i18n
3
+ Version: 0.1.0
4
+ Summary: Markdown i18n and l10n using markdown-it-py
5
+ Home-page: https://github.com/phunh/mdit-py-i18n
6
+ License: LGPL-2.1-or-later
7
+ Author: Phu Hung Nguyen
8
+ Author-email: phuhnguyen@outlook.com
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Topic :: Software Development :: Internationalization
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Dist: Pygments (>=2.16.1,<3.0.0)
21
+ Requires-Dist: markdown-it-py[plugins] (>=3.0.0,<4.0.0)
22
+ Project-URL: Repository, https://github.com/phunh/mdit-py-i18n
23
+ Description-Content-Type: text/markdown
24
+
25
+ <!--
26
+ SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
27
+ SPDX-License-Identifier: CC-BY-SA-4.0
28
+ -->
29
+
30
+ # mdit-py-i18n
31
+
32
+ Markdown i18n and l10n using markdown-it-py.
33
+
34
+ CommonMark compliant. All core Markdown elements are supported, as well as
35
+ table, and definition list. Front matter handlers are left for users to
36
+ implement.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install mdit-py-i18n
42
+ ```
43
+
44
+ ## Notes
45
+
46
+ Some notes about how different elements are handled:
47
+ - Inlines: newlines and consecutive spaces are not kept;
48
+ - Content of each HTML block isn't parsed into finer tokens but processed
49
+ as a whole;
50
+ - Fenced code blocks: only `//` single comments are processed;
51
+
52
+ ## Development
53
+
54
+ ### Environment
55
+
56
+ - With Conda
57
+
58
+ ```bash
59
+ conda env create -f environment.yml
60
+ conda activate mpi
61
+ poetry install
62
+ ```
63
+
64
+ ### Usage
65
+
66
+ #### Extraction
67
+ - Follow `I18NEntryProtocol` and `DomainExtractionProtocol`
68
+ - Subclass `RendererMarkdownI18N`
69
+
70
+ #### Generation
71
+ - Follow `DomainGenerationProtocol`
72
+ - Subclass `RendererMarkdownL10N`
@@ -0,0 +1,48 @@
1
+ <!--
2
+ SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
3
+ SPDX-License-Identifier: CC-BY-SA-4.0
4
+ -->
5
+
6
+ # mdit-py-i18n
7
+
8
+ Markdown i18n and l10n using markdown-it-py.
9
+
10
+ CommonMark compliant. All core Markdown elements are supported, as well as
11
+ table, and definition list. Front matter handlers are left for users to
12
+ implement.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install mdit-py-i18n
18
+ ```
19
+
20
+ ## Notes
21
+
22
+ Some notes about how different elements are handled:
23
+ - Inlines: newlines and consecutive spaces are not kept;
24
+ - Content of each HTML block isn't parsed into finer tokens but processed
25
+ as a whole;
26
+ - Fenced code blocks: only `//` single comments are processed;
27
+
28
+ ## Development
29
+
30
+ ### Environment
31
+
32
+ - With Conda
33
+
34
+ ```bash
35
+ conda env create -f environment.yml
36
+ conda activate mpi
37
+ poetry install
38
+ ```
39
+
40
+ ### Usage
41
+
42
+ #### Extraction
43
+ - Follow `I18NEntryProtocol` and `DomainExtractionProtocol`
44
+ - Subclass `RendererMarkdownI18N`
45
+
46
+ #### Generation
47
+ - Follow `DomainGenerationProtocol`
48
+ - Subclass `RendererMarkdownL10N`
@@ -0,0 +1,2 @@
1
+ # SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
2
+ # SPDX-License-Identifier: LGPL-2.1-or-later
@@ -0,0 +1,126 @@
1
+ # SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
2
+ # SPDX-License-Identifier: LGPL-2.1-or-later
3
+
4
+ import inspect
5
+ from typing import Sequence
6
+
7
+ import pygments.token
8
+ from markdown_it import MarkdownIt
9
+ from markdown_it.token import Token
10
+ from markdown_it.utils import OptionsDict, EnvType
11
+ from pygments import lexers, util
12
+
13
+ from . import utils
14
+ from .utils import DomainExtractionProtocol
15
+
16
+
17
+ class _MdCtx:
18
+ def __init__(self, env: EnvType):
19
+ self.path: str = env['path']
20
+ self.domain_e: DomainExtractionProtocol = env['domain_extraction']
21
+
22
+ def add_entry(self, msgid: str, line_number: int, comment: str = '', msgctxt: str = ''):
23
+ self.domain_e.add_entry(self.path, msgid, line_number, comment, msgctxt)
24
+
25
+
26
+ def _link_ref(env: EnvType, md_ctx: _MdCtx):
27
+ refs = env.get('references', {}).items()
28
+ if len(refs) == 0:
29
+ return
30
+ for ref, details in refs:
31
+ if title := details.get('title', ''):
32
+ # TODO: line number?
33
+ md_ctx.add_entry(title, 0)
34
+
35
+
36
+ class RendererMarkdownI18N:
37
+ """
38
+ Implements `RendererProtocol`
39
+ """
40
+ __output__ = 'pot'
41
+
42
+ def __init__(self, mdi: MarkdownIt):
43
+ self.rules = {
44
+ k: v
45
+ for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
46
+ if not (k.startswith("render") or k.startswith("_"))
47
+ }
48
+ self.mdi = mdi
49
+
50
+ def render(self, tokens: Sequence[Token], _options: OptionsDict, env: EnvType):
51
+ """
52
+ :param tokens: list of block tokens to render
53
+ :param _options: properties of parser instance
54
+ :param env: containing:
55
+ - 'path': path of the source file
56
+ - 'domain_extraction': an object compatible with `DomainExtractionProtocol`
57
+ :return: None
58
+ """
59
+ md_ctx = _MdCtx(env)
60
+
61
+ for i, token in enumerate(tokens):
62
+ if token.type in self.rules:
63
+ r = self.rules[token.type](tokens, i, md_ctx)
64
+ if r == -1:
65
+ break
66
+
67
+ _link_ref(env, md_ctx)
68
+
69
+ @classmethod
70
+ def front_matter(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx):
71
+ token = tokens[idx]
72
+ md_ctx.domain_e.render_front_matter(md_ctx.path, token.content, token.markup)
73
+
74
+ @classmethod
75
+ def inline(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx):
76
+ token = tokens[idx]
77
+ content = utils.SPACES_PATTERN.sub(' ', token.content.replace('\n', ' '))
78
+ if content and not utils.SPACES_PATTERN.fullmatch(content):
79
+ md_ctx.add_entry(content, token.map[0] + 1)
80
+
81
+ @classmethod
82
+ def fence(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx):
83
+ token = tokens[idx]
84
+ try:
85
+ lexer = lexers.get_lexer_by_name(token.info)
86
+ except util.ClassNotFound:
87
+ lexer = lexers.guess_lexer(token.content)
88
+ code_toks = lexer.get_tokens(token.content)
89
+
90
+ # temporary content of the comment being parsed
91
+ # also indicates whether we are parsing a comment or not
92
+ comment = ''
93
+ # number of the line where the comment starts
94
+ comment_line_num = 0
95
+ # number of the last line with a comment token
96
+ last_comment_line_num = 0
97
+ # the token starts with one line of the fence, then the content. +1: 0-base -> 1-base
98
+ line_num = token.map[0] + 1 + 1
99
+
100
+ # concatenate comment tokens until either a non-comment token or a blank line or end of token stream
101
+ for tok_type, tok_val in code_toks:
102
+ if tok_type == pygments.token.Token.Comment.Single:
103
+ # when another comment is already being parsed and there's a blank line
104
+ if comment and line_num - last_comment_line_num > 1:
105
+ md_ctx.add_entry(comment, comment_line_num)
106
+ comment = ''
107
+ comment_line_num = 0
108
+ if comment != '':
109
+ comment += ' '
110
+ if comment_match := utils.SINGLE_COMMENT_PATTERN.match(tok_val):
111
+ comment += comment_match.group(2).strip()
112
+ if comment_line_num == 0:
113
+ comment_line_num = line_num
114
+ last_comment_line_num = line_num
115
+ elif tok_val.strip() and comment:
116
+ md_ctx.add_entry(comment, comment_line_num)
117
+ comment = ''
118
+ comment_line_num = 0
119
+ line_num += tok_val.count('\n')
120
+ if comment:
121
+ md_ctx.add_entry(comment, comment_line_num)
122
+
123
+ @classmethod
124
+ def html_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx):
125
+ token = tokens[idx]
126
+ md_ctx.add_entry(token.content, token.map[0] + 1)
@@ -0,0 +1,382 @@
1
+ # SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
2
+ # SPDX-License-Identifier: LGPL-2.1-or-later
3
+
4
+ """Render localized markdown"""
5
+
6
+ import inspect
7
+ import textwrap
8
+ from dataclasses import dataclass
9
+ from typing import Sequence, Tuple, List
10
+
11
+ import pygments.token
12
+ from markdown_it import MarkdownIt
13
+ from markdown_it.token import Token
14
+ from markdown_it.utils import OptionsDict, EnvType
15
+ from pygments import lexers, util
16
+
17
+ from . import utils
18
+ from .utils import L10NResult, DomainGenerationProtocol
19
+
20
+ SETEXT_HEADING_MARKUPS = {'-', '='}
21
+ ORDERED_LIST_MARKUPS = {'.', ')'}
22
+
23
+
24
+ class _MdCtx:
25
+ def __init__(self, env: EnvType):
26
+ self.line_indent = ''
27
+ self.indent_1st_line = '' # list item, definition detail, atx heading
28
+ self.indent_1st_line_len = 0
29
+ self.indents: List[int] = []
30
+ self.setext_heading = ''
31
+ self.table_sep = ''
32
+ self.in_table = False
33
+ self.domain_g: DomainGenerationProtocol = env['domain_generation']
34
+
35
+ def get_line_indent(self):
36
+ if not self.indent_1st_line:
37
+ return self.line_indent
38
+ if self.indent_1st_line_len > 0:
39
+ line_indent = self.line_indent[:-self.indent_1st_line_len] + self.indent_1st_line
40
+ else:
41
+ line_indent = self.line_indent + self.indent_1st_line
42
+ self.indent_1st_line = ''
43
+ self.indent_1st_line_len = 0
44
+ return line_indent
45
+
46
+
47
+ @dataclass
48
+ class _FenceCtx:
49
+ localized: str = '' # the l10n result
50
+ # temporary content of the comment being parsed
51
+ # also indicates whether we are parsing a comment or not
52
+ comment: str = ''
53
+ indent: str = '' # things on the same line before the comment
54
+ next_indent: str = '' # a second field when 'indent' is busy
55
+
56
+
57
+ # TODO: parameterize: fence code comment i18n, wrap width, comment identifiers
58
+ # TODO: multiline comment?
59
+ def _fence_comment(fence_ctx: _FenceCtx, md_ctx: _MdCtx, content_result: L10NResult):
60
+ localized_comment = md_ctx.domain_g.l10n_func(fence_ctx.comment)
61
+ if localized_comment is not fence_ctx.comment:
62
+ content_result.l10n_count += 1
63
+ content_result.total_count += 1
64
+ subsequent_indent = ' ' * len(fence_ctx.indent) if fence_ctx.indent.strip() else fence_ctx.indent
65
+ comment_lines = textwrap.wrap(localized_comment,
66
+ 100,
67
+ initial_indent=f'{fence_ctx.indent}// ',
68
+ subsequent_indent=f'{subsequent_indent}// ')
69
+ for line in comment_lines:
70
+ fence_ctx.localized += f'{line}\n'
71
+ fence_ctx.comment = ''
72
+
73
+
74
+ def _fence(token: Token, md_ctx: _MdCtx, content_result: L10NResult):
75
+ try:
76
+ lexer = lexers.get_lexer_by_name(token.info)
77
+ except util.ClassNotFound:
78
+ lexer = lexers.guess_lexer(token.content)
79
+ code_toks = lexer.get_tokens(token.content)
80
+
81
+ # values to use in _fence_comment function
82
+ fence_ctx = _FenceCtx()
83
+ # number of the last line with a comment token
84
+ last_comment_line_num = 0
85
+ # the token starts with one line of the fence, then the content. +1: 0-base -> 1-base
86
+ line_num = token.map[0] + 1 + 1
87
+
88
+ # concatenate comment tokens until either a non-comment token or a blank line or end of token stream
89
+ for tok_type, tok_val in code_toks:
90
+ if tok_type == pygments.token.Token.Comment.Single:
91
+ # when another comment is already being parsed and there's a blank line
92
+ if fence_ctx.comment and line_num - last_comment_line_num > 1:
93
+ _fence_comment(fence_ctx, md_ctx, content_result)
94
+ last_nl = fence_ctx.next_indent.rfind('\n')
95
+ fence_ctx.localized += fence_ctx.next_indent[:last_nl + 1]
96
+ fence_ctx.indent = fence_ctx.next_indent[last_nl + 1:]
97
+ if fence_ctx.comment != '':
98
+ fence_ctx.comment += ' '
99
+ if comment_match := utils.SINGLE_COMMENT_PATTERN.match(tok_val):
100
+ fence_ctx.comment += comment_match.group(2).strip()
101
+ last_comment_line_num = line_num
102
+ else:
103
+ if fence_ctx.comment:
104
+ if tok_val.strip():
105
+ _fence_comment(fence_ctx, md_ctx, content_result)
106
+ fence_ctx.indent = fence_ctx.next_indent + tok_val
107
+ fence_ctx.next_indent = ''
108
+ else:
109
+ fence_ctx.next_indent = tok_val
110
+ else:
111
+ last_nl = tok_val.rfind('\n')
112
+ if last_nl != -1:
113
+ fence_ctx.localized += fence_ctx.indent + tok_val[:last_nl + 1]
114
+ fence_ctx.indent = tok_val[last_nl + 1:]
115
+ else:
116
+ fence_ctx.indent += tok_val
117
+ line_num += tok_val.count('\n')
118
+ if fence_ctx.comment:
119
+ _fence_comment(fence_ctx, md_ctx, content_result)
120
+ return fence_ctx.localized
121
+
122
+
123
+ def _front_matter(token: Token, env: EnvType) -> L10NResult:
124
+ domain_g: DomainGenerationProtocol = env['domain_generation']
125
+ fm_result = domain_g.render_front_matter(token.content, token.markup)
126
+ return fm_result
127
+
128
+
129
+ def _link_ref(env: EnvType, md_ctx: _MdCtx, content_result: L10NResult):
130
+ refs = env.get('references', {}).items()
131
+ if len(refs) == 0:
132
+ return
133
+ content_result.localized += '\n'
134
+ for ref, details in refs:
135
+ href = details['href']
136
+ content_result.localized += f'[{ref}]: {href}'
137
+ if title := details.get('title', ''):
138
+ localized_title = md_ctx.domain_g.l10n_func(title)
139
+ if localized_title is not title:
140
+ content_result.l10n_count += 1
141
+ content_result.total_count += 1
142
+ content_result.localized += f' "{localized_title}"'
143
+ content_result.localized += '\n'
144
+
145
+
146
+ class RendererMarkdownL10N:
147
+ """
148
+ Implements `RendererProtocol`
149
+ """
150
+ __output__ = 'md'
151
+
152
+ def __init__(self, mdi: MarkdownIt):
153
+ self.rules = {
154
+ k: v
155
+ for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
156
+ if not (k.startswith("render") or k.startswith("_"))
157
+ }
158
+ self.mdi = mdi
159
+
160
+ def render(self, tokens: Sequence[Token], _options: OptionsDict, env: EnvType) -> Tuple[L10NResult, L10NResult]:
161
+ """
162
+ :param tokens: list of block tokens to render
163
+ :param _options: properties of parser instance
164
+ :param env: containing 'domain_generation' an object compatible with `DomainGenerationProtocol`
165
+ :return: an `L10NResult`
166
+ """
167
+ if tokens[0].type == 'front_matter':
168
+ fm_result = _front_matter(tokens[0], env)
169
+ tokens = tokens[1:]
170
+ else:
171
+ fm_result = L10NResult('', 0, 0)
172
+
173
+ md_ctx = _MdCtx(env)
174
+ content_result = L10NResult('', 0, 0)
175
+
176
+ for i, token in enumerate(tokens):
177
+ if token.type in self.rules:
178
+ r = self.rules[token.type](tokens, i, md_ctx, content_result)
179
+ if r == -1:
180
+ break
181
+
182
+ _link_ref(env, md_ctx, content_result)
183
+
184
+ return fm_result, content_result
185
+
186
+ @classmethod
187
+ def inline(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
188
+ token = tokens[idx]
189
+ content = utils.SPACES_PATTERN.sub(' ', token.content.replace('\n', ' '))
190
+ if content and not utils.SPACES_PATTERN.fullmatch(content):
191
+ localized_content = md_ctx.domain_g.l10n_func(content)
192
+ else:
193
+ localized_content = content
194
+ if localized_content is not content:
195
+ content_result.l10n_count += 1
196
+ content_result.total_count += 1
197
+ if md_ctx.in_table:
198
+ content_result.localized += localized_content
199
+ else:
200
+ content_result.localized += f'{md_ctx.get_line_indent()}{localized_content}'
201
+
202
+ # blockquote
203
+ # TODO: blockquote inside list
204
+ @classmethod
205
+ def blockquote_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult):
206
+ token = tokens[idx]
207
+ md_ctx.line_indent = f'{md_ctx.get_line_indent()}{token.markup} '
208
+
209
+ @classmethod
210
+ def blockquote_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
211
+ md_ctx.line_indent = md_ctx.line_indent[:-2]
212
+ content_result.localized += f'{md_ctx.line_indent}\n'
213
+
214
+ # heading
215
+ @classmethod
216
+ def heading_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult):
217
+ token = tokens[idx]
218
+ if token.markup not in SETEXT_HEADING_MARKUPS:
219
+ md_ctx.indent_1st_line += f'{token.markup} '
220
+ # md_ctx.indent_1st_line_len += 0
221
+ # md_ctx.line_indent += ' ' * 0
222
+ md_ctx.indents.append(0)
223
+ else:
224
+ md_ctx.setext_heading = token.markup
225
+
226
+ @classmethod
227
+ def heading_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
228
+ if md_ctx.setext_heading:
229
+ content_result.localized += f'\n{md_ctx.get_line_indent()}{md_ctx.setext_heading}'
230
+ md_ctx.setext_heading = ''
231
+ else:
232
+ md_ctx.indents.pop()
233
+ # the added len is 0, so line_indent remains the same
234
+ content_result.localized += '\n'
235
+
236
+ # thematic break
237
+ @classmethod
238
+ def hr(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
239
+ token = tokens[idx]
240
+ # always use '_' here to differentiate this from setext headings and bullet list items
241
+ content_result.localized += f'{md_ctx.get_line_indent()}{len(token.markup) * "_"}\n'
242
+
243
+ # list
244
+ # TODO: loose lists?
245
+ @classmethod
246
+ def list_item_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult):
247
+ token = tokens[idx]
248
+ markup = f'{token.info}{token.markup}' if token.markup in ORDERED_LIST_MARKUPS else f'{token.markup}'
249
+ md_ctx.indent_1st_line += f'{markup} '
250
+ added_len = len(markup) + 1
251
+ md_ctx.indent_1st_line_len += added_len
252
+ md_ctx.line_indent += ' ' * added_len
253
+ md_ctx.indents.append(added_len)
254
+
255
+ @classmethod
256
+ def list_item_close(cls,
257
+ _tokens: Sequence[Token],
258
+ _idx: int,
259
+ md_ctx: _MdCtx,
260
+ _content_result: L10NResult):
261
+ latest_len = md_ctx.indents.pop()
262
+ md_ctx.line_indent = md_ctx.line_indent[:-latest_len]
263
+
264
+ @classmethod
265
+ def bullet_list_close(cls,
266
+ tokens: Sequence[Token],
267
+ idx: int,
268
+ md_ctx: _MdCtx,
269
+ content_result: L10NResult):
270
+ # add a blank line when next token is not a closing one
271
+ if idx < len(tokens) - 1 and tokens[idx + 1].nesting != -1:
272
+ content_result.localized += f'{md_ctx.line_indent}\n'
273
+
274
+ @classmethod
275
+ def ordered_list_close(cls,
276
+ tokens: Sequence[Token],
277
+ idx: int,
278
+ md_ctx: _MdCtx,
279
+ content_result: L10NResult):
280
+ # add a blank line when next token is not a closing one
281
+ if idx < len(tokens) - 1 and tokens[idx + 1].nesting != -1:
282
+ content_result.localized += f'{md_ctx.line_indent}\n'
283
+
284
+ # paragraph
285
+ @classmethod
286
+ def paragraph_close(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
287
+ content_result.localized += '\n'
288
+ if idx < len(tokens) - 1:
289
+ next_token = tokens[idx + 1]
290
+ # add a blank line when next token is a setext heading_open, an indented code block, a paragraph open,
291
+ # or a definition list open
292
+ if (next_token.type == 'heading_open' and next_token.markup in SETEXT_HEADING_MARKUPS) \
293
+ or next_token.type in {'code_block', 'paragraph_open', 'dl_open'}:
294
+ content_result.localized += f'{md_ctx.line_indent}\n'
295
+
296
+ # indented code block
297
+ @classmethod
298
+ def code_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
299
+ token = tokens[idx]
300
+ localized_code_block = token.content.replace('\n', f'\n{md_ctx.line_indent} ')
301
+ content_result.localized += f'{md_ctx.get_line_indent()} {localized_code_block}\n'
302
+
303
+ # fenced code block
304
+ @classmethod
305
+ def fence(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
306
+ token = tokens[idx]
307
+ localized_fence = _fence(token, md_ctx, content_result)
308
+ localized_fence = localized_fence.replace('\n', f'\n{md_ctx.line_indent}')
309
+ # a newline is at the end of token.content already, so we only need to append token.markup there
310
+ content_result.localized += f'''{md_ctx.get_line_indent()}{token.markup}{token.info}
311
+ {md_ctx.line_indent}{localized_fence}{token.markup}
312
+ '''
313
+
314
+ # html block
315
+ @classmethod
316
+ def html_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult):
317
+ token = tokens[idx]
318
+ localized_html = md_ctx.domain_g.l10n_func(token.content)
319
+ if localized_html is not token.content:
320
+ content_result.l10n_count += 1
321
+ content_result.total_count += 1
322
+ localized_html = localized_html.replace('\n', f'\n{md_ctx.line_indent}')
323
+ content_result.localized += f'{md_ctx.get_line_indent()}{localized_html}\n'
324
+
325
+ # table
326
+ @classmethod
327
+ def table_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, _content_result: L10NResult):
328
+ md_ctx.in_table = True
329
+
330
+ @classmethod
331
+ def tr_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
332
+ content_result.localized += f'{md_ctx.get_line_indent()}|'
333
+
334
+ @classmethod
335
+ def th_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
336
+ content_result.localized += ' '
337
+ md_ctx.table_sep += '| --- '
338
+
339
+ @classmethod
340
+ def th_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult):
341
+ content_result.localized += ' |'
342
+
343
+ @classmethod
344
+ def thead_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
345
+ md_ctx.table_sep += '|\n'
346
+ content_result.localized += f'{md_ctx.line_indent}{md_ctx.table_sep}'
347
+ md_ctx.table_sep = ''
348
+
349
+ @classmethod
350
+ def td_open(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult):
351
+ content_result.localized += ' '
352
+
353
+ @classmethod
354
+ def td_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult):
355
+ content_result.localized += ' |'
356
+
357
+ @classmethod
358
+ def tr_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult):
359
+ content_result.localized += '\n'
360
+
361
+ @classmethod
362
+ def table_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
363
+ content_result.localized += f'{md_ctx.line_indent}\n'
364
+ md_ctx.in_table = False
365
+
366
+ # definition list
367
+ @classmethod
368
+ def dd_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, _content_result: L10NResult):
369
+ md_ctx.indent_1st_line += f': '
370
+ md_ctx.indent_1st_line_len += 2
371
+ md_ctx.line_indent += ' ' * 2
372
+ md_ctx.indents.append(2)
373
+
374
+ @classmethod
375
+ def dd_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult):
376
+ latest_len = md_ctx.indents.pop()
377
+ md_ctx.line_indent = md_ctx.line_indent[:-latest_len]
378
+ content_result.localized += f'{md_ctx.line_indent}\n'
379
+
380
+ @classmethod
381
+ def dt_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult):
382
+ content_result.localized += '\n'
@@ -0,0 +1,61 @@
1
+ # SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
2
+ # SPDX-License-Identifier: LGPL-2.1-or-later
3
+
4
+ import re
5
+
6
+ from typing import Callable, Protocol, Tuple, List
7
+
8
+ SPACES_PATTERN = re.compile(r'\s+')
9
+ SINGLE_COMMENT_PATTERN = re.compile('(// *)(.*)')
10
+
11
+
12
+ # extraction
13
+ class I18NEntryProtocol(Protocol):
14
+ msgid: str
15
+ occurrences: List[Tuple[str, int]]
16
+ comment: str
17
+ msgctxt: str
18
+
19
+
20
+ class DomainExtractionProtocol(Protocol):
21
+ entries: List[I18NEntryProtocol]
22
+
23
+ def add_entry(self, path: str, msgid: str, line_num: int, comment: str = '', msgctxt: str = ''):
24
+ ...
25
+
26
+ def render_front_matter(self, path: str, content: str, markup: str):
27
+ ...
28
+
29
+
30
+ # generation
31
+ class L10NResult:
32
+ """Localized content, total number of messages, number of translations.
33
+ If there are no messages, rate will be -1
34
+ """
35
+ def __init__(self, localized, total_count: int, l10n_count: int):
36
+ self.localized = localized
37
+ self.total_count = total_count
38
+ self.l10n_count = l10n_count
39
+
40
+ def __str__(self):
41
+ return f'({self.l10n_count}/{self.total_count})'
42
+
43
+ def __add__(self, other: 'L10NResult'):
44
+ localized = self.localized + other.localized
45
+ total_count = self.total_count + other.total_count
46
+ l10n_count = self.l10n_count + other.l10n_count
47
+ return L10NResult(localized, total_count, l10n_count)
48
+
49
+ @property
50
+ def rate(self):
51
+ return self.l10n_count / self.total_count if self.total_count > 0 else -1
52
+
53
+
54
+ L10NFunc = Callable[[str], str]
55
+
56
+
57
+ class DomainGenerationProtocol(Protocol):
58
+ l10n_func: L10NFunc
59
+
60
+ def render_front_matter(self, content: str, markup: str):
61
+ ...
@@ -0,0 +1,29 @@
1
+ # SPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>
2
+ # SPDX-License-Identifier: CC0-1.0
3
+
4
+ [tool.poetry]
5
+ name = "mdit-py-i18n"
6
+ version = "0.1.0"
7
+ description = "Markdown i18n and l10n using markdown-it-py"
8
+ authors = ["Phu Hung Nguyen <phuhnguyen@outlook.com>"]
9
+ license = "LGPL-2.1-or-later"
10
+ readme = "README.md"
11
+ repository = "https://github.com/phunh/mdit-py-i18n"
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Topic :: Software Development :: Libraries",
16
+ "Topic :: Software Development :: Internationalization",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3"
19
+ ]
20
+ packages = [{include = "mdit_py_i18n"}]
21
+
22
+ [tool.poetry.dependencies]
23
+ python = "^3.8"
24
+ markdown-it-py = {extras = ["plugins"], version = "^3.0.0"}
25
+ Pygments = "^2.16.1"
26
+
27
+ [build-system]
28
+ requires = ["poetry-core"]
29
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,30 @@
1
+ # -*- coding: utf-8 -*-
2
+ from setuptools import setup
3
+
4
+ packages = \
5
+ ['mdit_py_i18n']
6
+
7
+ package_data = \
8
+ {'': ['*']}
9
+
10
+ install_requires = \
11
+ ['Pygments>=2.16.1,<3.0.0', 'markdown-it-py[plugins]>=3.0.0,<4.0.0']
12
+
13
+ setup_kwargs = {
14
+ 'name': 'mdit-py-i18n',
15
+ 'version': '0.1.0',
16
+ 'description': 'Markdown i18n and l10n using markdown-it-py',
17
+ 'long_description': "<!--\nSPDX-FileCopyrightText: 2023 Phu Hung Nguyen <phuhnguyen@outlook.com>\nSPDX-License-Identifier: CC-BY-SA-4.0\n-->\n\n# mdit-py-i18n\n\nMarkdown i18n and l10n using markdown-it-py.\n\nCommonMark compliant. All core Markdown elements are supported, as well as\ntable, and definition list. Front matter handlers are left for users to\nimplement.\n\n## Install\n\n```bash\npip install mdit-py-i18n\n```\n\n## Notes\n\nSome notes about how different elements are handled:\n- Inlines: newlines and consecutive spaces are not kept;\n- Content of each HTML block isn't parsed into finer tokens but processed\nas a whole;\n- Fenced code blocks: only `//` single comments are processed;\n\n## Development\n\n### Environment\n\n- With Conda\n\n```bash\nconda env create -f environment.yml\nconda activate mpi\npoetry install\n```\n\n### Usage\n\n#### Extraction\n- Follow `I18NEntryProtocol` and `DomainExtractionProtocol`\n- Subclass `RendererMarkdownI18N`\n\n#### Generation\n- Follow `DomainGenerationProtocol`\n- Subclass `RendererMarkdownL10N`",
18
+ 'author': 'Phu Hung Nguyen',
19
+ 'author_email': 'phuhnguyen@outlook.com',
20
+ 'maintainer': None,
21
+ 'maintainer_email': None,
22
+ 'url': 'https://github.com/phunh/mdit-py-i18n',
23
+ 'packages': packages,
24
+ 'package_data': package_data,
25
+ 'install_requires': install_requires,
26
+ 'python_requires': '>=3.8,<4.0',
27
+ }
28
+
29
+
30
+ setup(**setup_kwargs)