clld-markdown-plugin 0.5.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.1
2
+ Name: clld_markdown_plugin
3
+ Version: 0.5.0
4
+ Summary: Render CLDF markdown in clld apps.
5
+ Home-page: https://github.com/clld/clld-markdown-plugin
6
+ Author: Robert Forkel, Florian Matter
7
+ Author-email: robert_forkel@eva.mpg.de, florianmatter@gmail.com
8
+ Project-URL: Bug Tracker, https://github.com/clld/clld-markdown-plugin/issues
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: dev
21
+ Provides-Extra: test
22
+ License-File: LICENSE
23
+
24
+ # clld-markdown-plugin
25
+
26
+ Render [CLDF markdown](https://github.com/cldf/cldf/blob/master/extensions/markdown.md) in clld apps
27
+
28
+ ## Usage
29
+
30
+ Include (and configure the plugin) in your app's `main` function:
31
+ ```python
32
+ def main(global_config, **settings):
33
+ settings['clld_markdown_plugin'] = {
34
+ 'model_map': {'ValueTable': common.ValueSet},
35
+ 'function_map': {}
36
+ }
37
+ config = Configurator(settings=settings)
38
+ config.include('clld.web.app')
39
+ ...
40
+ config.include('clld_markdown_plugin')
41
+ ```
42
+
43
+ Then you can use `clld_markdown_plugin.markup` as follows in your templates:
44
+ ```html
45
+ <%! from clld_markdown_plugin import markdown %>
46
+
47
+ ${markdown(req, '[x](LanguageTable#cldf:abad1241)')|n}
48
+ ```
49
+
50
+ By default, links to objects in the CLDF dataset will be rendered as HTML links to the corresponding
51
+ object's details page in the clld app.
52
+
53
+
54
+ ### Configuration
55
+
56
+ The plugin can be configured via the following four configuration options:
57
+
58
+ - `model_map`: A `dict` mapping CLDF component names to DB model classes defined for the app. This
59
+ allows for a flexible mapping between CLDF components and the clld DB classes.
60
+ - `renderer_map`: See below for details.
61
+ - `extensions`: A list of [markdown extensions](https://python-markdown.github.io/extensions/#officially-supported-extensions)
62
+ in dot notation, to be activated when calling the `markdown` function.
63
+ - `keep_link_labels`: A `boolean` indicating whether to keep link labels as they appear in the
64
+ CLDF Markdown text. By default (`False`), labels will be substituted using the linked object's
65
+ name.
66
+
67
+
68
+ #### Renderer callables
69
+
70
+ The `renderer_map` configuration option for `clld_markdown_plugin` accepts a `dict` mapping
71
+ CLDF component names to Python callables with the following signature:
72
+
73
+ ```python
74
+ import clld.web.app
75
+
76
+
77
+ def renderer(req: clld.web.app.ClldRequest, objid: str, table, session: clld.db.meta.DBSession, ids=None) -> str:
78
+ """
79
+ The returned `str` is interpreted as Markdown, so it may also include HTML.
80
+ """
81
+ ```
@@ -0,0 +1,58 @@
1
+ # clld-markdown-plugin
2
+
3
+ Render [CLDF markdown](https://github.com/cldf/cldf/blob/master/extensions/markdown.md) in clld apps
4
+
5
+ ## Usage
6
+
7
+ Include (and configure the plugin) in your app's `main` function:
8
+ ```python
9
+ def main(global_config, **settings):
10
+ settings['clld_markdown_plugin'] = {
11
+ 'model_map': {'ValueTable': common.ValueSet},
12
+ 'function_map': {}
13
+ }
14
+ config = Configurator(settings=settings)
15
+ config.include('clld.web.app')
16
+ ...
17
+ config.include('clld_markdown_plugin')
18
+ ```
19
+
20
+ Then you can use `clld_markdown_plugin.markup` as follows in your templates:
21
+ ```html
22
+ <%! from clld_markdown_plugin import markdown %>
23
+
24
+ ${markdown(req, '[x](LanguageTable#cldf:abad1241)')|n}
25
+ ```
26
+
27
+ By default, links to objects in the CLDF dataset will be rendered as HTML links to the corresponding
28
+ object's details page in the clld app.
29
+
30
+
31
+ ### Configuration
32
+
33
+ The plugin can be configured via the following four configuration options:
34
+
35
+ - `model_map`: A `dict` mapping CLDF component names to DB model classes defined for the app. This
36
+ allows for a flexible mapping between CLDF components and the clld DB classes.
37
+ - `renderer_map`: See below for details.
38
+ - `extensions`: A list of [markdown extensions](https://python-markdown.github.io/extensions/#officially-supported-extensions)
39
+ in dot notation, to be activated when calling the `markdown` function.
40
+ - `keep_link_labels`: A `boolean` indicating whether to keep link labels as they appear in the
41
+ CLDF Markdown text. By default (`False`), labels will be substituted using the linked object's
42
+ name.
43
+
44
+
45
+ #### Renderer callables
46
+
47
+ The `renderer_map` configuration option for `clld_markdown_plugin` accepts a `dict` mapping
48
+ CLDF component names to Python callables with the following signature:
49
+
50
+ ```python
51
+ import clld.web.app
52
+
53
+
54
+ def renderer(req: clld.web.app.ClldRequest, objid: str, table, session: clld.db.meta.DBSession, ids=None) -> str:
55
+ """
56
+ The returned `str` is interpreted as Markdown, so it may also include HTML.
57
+ """
58
+ ```
@@ -0,0 +1,4 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
@@ -0,0 +1,81 @@
1
+ [metadata]
2
+ version = 0.5.0
3
+ author = Robert Forkel, Florian Matter
4
+ author_email = robert_forkel@eva.mpg.de, florianmatter@gmail.com
5
+ classifiers =
6
+ Development Status :: 2 - Pre-Alpha
7
+ Intended Audience :: Science/Research
8
+ License :: OSI Approved :: Apache Software License
9
+ Natural Language :: English
10
+ Programming Language :: Python :: 3
11
+ Programming Language :: Python :: 3.8
12
+ Programming Language :: Python :: 3.9
13
+ Programming Language :: Python :: 3.10
14
+ Programming Language :: Python :: 3.11
15
+ Programming Language :: Python :: 3.12
16
+ description = Render CLDF markdown in clld apps.
17
+ long_description = file: README.md
18
+ long_description_content_type = text/markdown
19
+ name = clld_markdown_plugin
20
+ project_urls =
21
+ Bug Tracker = https://github.com/clld/clld-markdown-plugin/issues
22
+ url = https://github.com/clld/clld-markdown-plugin
23
+
24
+ [options]
25
+ zip_safe = False
26
+ include_package_data = True
27
+ packages = find:
28
+ package_dir =
29
+ =src
30
+ install_requires =
31
+ clldutils
32
+ pycldf
33
+ clld
34
+ markdown
35
+
36
+ [options.extras_require]
37
+ dev =
38
+ flake8
39
+ twine
40
+ wheel
41
+ build
42
+ test =
43
+ pytest
44
+ pytest-mock
45
+ pytest-cov
46
+ tox
47
+
48
+ [options.packages.find]
49
+ include = clld_markdown_plugin, clld_markdown_plugin.*
50
+ where = src
51
+
52
+ [flake8]
53
+ max-line-length = 100
54
+ extend-ignore = E203
55
+
56
+ [tool:pytest]
57
+ addopts = --cov
58
+ testpaths = tests
59
+ filterwarnings =
60
+ ignore::sqlalchemy.exc.RemovedIn20Warning
61
+
62
+ [coverage:run]
63
+ source =
64
+ clld_markdown_plugin
65
+
66
+ [coverage:report]
67
+ show_missing = true
68
+
69
+ [tox:tox]
70
+ envlist = py38, py39, py310, py311, py312
71
+ isolated_build = true
72
+ skip_missing_interpreter = true
73
+
74
+ [testenv]
75
+ deps = .[test]
76
+ commands = pytest {posargs}
77
+
78
+ [egg_info]
79
+ tag_build =
80
+ tag_date = 0
81
+
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env python
2
+
3
+ import setuptools
4
+
5
+ if __name__ == "__main__":
6
+ setuptools.setup()
@@ -0,0 +1,177 @@
1
+ """Top-level package for clld-markdown-plugin."""
2
+ import typing
3
+ import logging
4
+
5
+ from markdown import Markdown
6
+ from markdown import markdown as base_markdown
7
+ from pycldf.ext.markdown import CLDFMarkdownLink
8
+ from clld.db.meta import DBSession
9
+ from clld.db.models import common
10
+ from clld.web.util.helpers import rendered_sentence
11
+ from clld.web.util.htmllib import HTML, literal
12
+ import clldutils
13
+
14
+ WITH_MARKDOWN = tuple(map(int, clldutils.__version__.split('.')[:2])) >= (3, 21)
15
+ log = logging.getLogger(__name__)
16
+
17
+ __author__ = "Robert Forkel, Florian Matter"
18
+ __email__ = "robert_forkel@eva.mpg.de, florianmatter@gmail.com"
19
+ __version__ = "0.5.0"
20
+ __all__ = ['markdown', 'includeme']
21
+
22
+
23
+ def settings(custom: typing.Optional[dict] = None) -> dict:
24
+ def full_spec(spec):
25
+ return spec if isinstance(spec, dict) else {
26
+ 'route': spec.__name__.split('.')[-1].lower() if spec else '', 'model': spec}
27
+
28
+ res = {
29
+ 'model_map': {
30
+ "LanguageTable": full_spec(common.Language),
31
+ "ParameterTable": full_spec(common.Parameter),
32
+ "ValueTable": full_spec(common.Value),
33
+ "FormTable": full_spec(common.Unit),
34
+ "ExampleTable": full_spec(common.Sentence),
35
+ "ContributionTable": full_spec(common.Contribution),
36
+ "CognatesetTable": full_spec(common.UnitParameter),
37
+ "sources.bib": full_spec(common.Source),
38
+ "Source": full_spec(common.Source),
39
+ },
40
+ 'renderer_map': {
41
+ "ExampleTable": render_ex,
42
+ },
43
+ "extensions": [
44
+ "markdown.extensions.fenced_code",
45
+ "markdown.extensions.tables",
46
+ ],
47
+ "keep_link_labels": False,
48
+ }
49
+ custom = custom or {}
50
+ for key in res:
51
+ if key == 'model_map':
52
+ for k, v in custom.get(key, {}).items():
53
+ res[key][k] = full_spec(v)
54
+ elif key == "renderer_map":
55
+ res[key].update(custom.get(key, {}))
56
+ elif key == "extensions":
57
+ res[key].extend(custom.get(key, []))
58
+ elif key in custom:
59
+ res[key] = custom[key]
60
+ return res
61
+
62
+
63
+ def includeme(config):
64
+ """
65
+ Called when the plugin is included in a clld app via `config.include('clld_markdown_plugin')`.
66
+
67
+ Merges default and custom configuration for the plugin in the app's deployment settings under
68
+ key 'clld_markdown_plugin'.
69
+
70
+ .. seealso:: https://docs.pylonsproject.org/projects/pyramid/en/latest/api/registry.html\
71
+ #pyramid.registry.Registry.settings
72
+
73
+ :param config: `pyramid.config.Configurator`
74
+ :return: `pyramid.config.Configurator` with updated settings for `clld_markdown_plugin`.
75
+ """
76
+ config.registry.settings[__name__] = settings(
77
+ config.registry.settings.get(__name__))
78
+ return config
79
+
80
+
81
+ def comma_and_list(entries, sep1=", ", sep2=" and "):
82
+ output = entries[0]
83
+ for entry in entries[1:-1]:
84
+ output += sep1 + entry
85
+ return output + sep2 + entries[-1]
86
+
87
+
88
+ def link_entity(req, objid, route, model, session, decorate=None, ids=None, **kwargs):
89
+ if objid == "__all__":
90
+ if ids:
91
+ md_strs = [
92
+ link_entity(req, mid, route, model, session, decorate=decorate, **kwargs)
93
+ for mid in ids[0].split(",")
94
+ ]
95
+ return comma_and_list(md_strs)
96
+ raise NotImplementedError("Table not yet implemented") # pragma: no cover
97
+ else:
98
+ try:
99
+ entity = session.query(model).filter(model.id == objid)[0]
100
+ except IndexError:
101
+ raise ValueError(objid) # pragma: no cover
102
+ label = kwargs.pop("label", [None])[0]
103
+ anchor = kwargs.pop("_anchor", [None])[0]
104
+ url = req.route_url(route, id=objid, _anchor=anchor, **kwargs)
105
+ md_str = '<a class="{}" href="{}">{}</a>'.format(
106
+ model.__tablename__.capitalize(), url, label or entity.name)
107
+ return decorate(md_str) if decorate else md_str
108
+
109
+
110
+ def render_ex(req, objid, table, session, ids=None, **kw):
111
+ if objid == "__all__":
112
+ if ids:
113
+ ex_strs = [
114
+ render_ex(req, mid, table, session, subexample=True) for mid in ids[0].split(",")
115
+ ]
116
+ return '\n\n'.join(ex_strs)
117
+ return rendered_sentence(session.query(common.Sentence).filter(common.Sentence.id == objid)[0])
118
+
119
+
120
+ def markdown(req, s: str, session=None) -> str:
121
+ """
122
+ :param req:
123
+ :param s:
124
+ :param permalink:
125
+ :param session:
126
+ :return: `str` containing HTML formatting.
127
+ """
128
+ if __name__ not in req.registry.settings: # pragma: no cover
129
+ raise KeyError(
130
+ '{} must be included in the app config to use the "markdown" function.'.format(
131
+ __name__))
132
+ settings = req.registry.settings[__name__]
133
+ source_ids = set()
134
+
135
+ def repl(ml):
136
+ def ref(src): # pragma: no cover
137
+ if WITH_MARKDOWN:
138
+ return base_markdown(src.bibtex().text(markdown=True))
139
+ return src.bibtex().text()
140
+
141
+ if ml.is_cldf_link:
142
+ try:
143
+ table = ml.table_or_fname
144
+ if table in settings['renderer_map'] and "as_link" not in ml.parsed_url_query:
145
+ return settings['renderer_map'][table](
146
+ req, ml.objid, table, session or DBSession, **ml.parsed_url_query)
147
+ elif table in settings['model_map']:
148
+ decorate = settings['model_map'][table].get("decorate", None)
149
+ kw = {k: v for k, v in ml.parsed_url_query.items()}
150
+ if ml.label and settings['keep_link_labels']:
151
+ kw.setdefault('label', [ml.label])
152
+ if table == 'Source':
153
+ if ml.objid != '__all__':
154
+ source_ids.add(ml.objid)
155
+ elif 'cited_only' in ml.parsed_url.query:
156
+ model = settings['model_map'][table]["model"]
157
+ return HTML.ul(*[
158
+ HTML.li(literal(ref(
159
+ (session or DBSession).query(model).filter(model.id == sid)[0]
160
+ )))
161
+ for sid in sorted(source_ids)])
162
+ return link_entity(
163
+ req,
164
+ ml.objid,
165
+ settings['model_map'][table]["route"],
166
+ settings['model_map'][table]["model"],
167
+ session or DBSession,
168
+ decorate=decorate,
169
+ **kw,
170
+ )
171
+ log.error(f"Can't handle [{ml.objid}] ({table}).")
172
+ return f"{table}:{ml.objid}"
173
+ except: # noqa: E722
174
+ return ml.label
175
+ return ml
176
+
177
+ return Markdown(extensions=settings["extensions"]).convert(CLDFMarkdownLink.replace(s, repl))
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.1
2
+ Name: clld-markdown-plugin
3
+ Version: 0.5.0
4
+ Summary: Render CLDF markdown in clld apps.
5
+ Home-page: https://github.com/clld/clld-markdown-plugin
6
+ Author: Robert Forkel, Florian Matter
7
+ Author-email: robert_forkel@eva.mpg.de, florianmatter@gmail.com
8
+ Project-URL: Bug Tracker, https://github.com/clld/clld-markdown-plugin/issues
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: dev
21
+ Provides-Extra: test
22
+ License-File: LICENSE
23
+
24
+ # clld-markdown-plugin
25
+
26
+ Render [CLDF markdown](https://github.com/cldf/cldf/blob/master/extensions/markdown.md) in clld apps
27
+
28
+ ## Usage
29
+
30
+ Include (and configure the plugin) in your app's `main` function:
31
+ ```python
32
+ def main(global_config, **settings):
33
+ settings['clld_markdown_plugin'] = {
34
+ 'model_map': {'ValueTable': common.ValueSet},
35
+ 'function_map': {}
36
+ }
37
+ config = Configurator(settings=settings)
38
+ config.include('clld.web.app')
39
+ ...
40
+ config.include('clld_markdown_plugin')
41
+ ```
42
+
43
+ Then you can use `clld_markdown_plugin.markup` as follows in your templates:
44
+ ```html
45
+ <%! from clld_markdown_plugin import markdown %>
46
+
47
+ ${markdown(req, '[x](LanguageTable#cldf:abad1241)')|n}
48
+ ```
49
+
50
+ By default, links to objects in the CLDF dataset will be rendered as HTML links to the corresponding
51
+ object's details page in the clld app.
52
+
53
+
54
+ ### Configuration
55
+
56
+ The plugin can be configured via the following four configuration options:
57
+
58
+ - `model_map`: A `dict` mapping CLDF component names to DB model classes defined for the app. This
59
+ allows for a flexible mapping between CLDF components and the clld DB classes.
60
+ - `renderer_map`: See below for details.
61
+ - `extensions`: A list of [markdown extensions](https://python-markdown.github.io/extensions/#officially-supported-extensions)
62
+ in dot notation, to be activated when calling the `markdown` function.
63
+ - `keep_link_labels`: A `boolean` indicating whether to keep link labels as they appear in the
64
+ CLDF Markdown text. By default (`False`), labels will be substituted using the linked object's
65
+ name.
66
+
67
+
68
+ #### Renderer callables
69
+
70
+ The `renderer_map` configuration option for `clld_markdown_plugin` accepts a `dict` mapping
71
+ CLDF component names to Python callables with the following signature:
72
+
73
+ ```python
74
+ import clld.web.app
75
+
76
+
77
+ def renderer(req: clld.web.app.ClldRequest, objid: str, table, session: clld.db.meta.DBSession, ids=None) -> str:
78
+ """
79
+ The returned `str` is interpreted as Markdown, so it may also include HTML.
80
+ """
81
+ ```
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ setup.py
6
+ src/clld_markdown_plugin/__init__.py
7
+ src/clld_markdown_plugin.egg-info/PKG-INFO
8
+ src/clld_markdown_plugin.egg-info/SOURCES.txt
9
+ src/clld_markdown_plugin.egg-info/dependency_links.txt
10
+ src/clld_markdown_plugin.egg-info/not-zip-safe
11
+ src/clld_markdown_plugin.egg-info/requires.txt
12
+ src/clld_markdown_plugin.egg-info/top_level.txt
13
+ tests/test_unit.py
@@ -0,0 +1,16 @@
1
+ clldutils
2
+ pycldf
3
+ clld
4
+ markdown
5
+
6
+ [dev]
7
+ flake8
8
+ twine
9
+ wheel
10
+ build
11
+
12
+ [test]
13
+ pytest
14
+ pytest-mock
15
+ pytest-cov
16
+ tox
@@ -0,0 +1,38 @@
1
+ import pytest
2
+
3
+ from clld_markdown_plugin import *
4
+
5
+
6
+ @pytest.mark.parametrize(
7
+ 'model_map,renderer_map,md,substring,notsubstring',
8
+ [
9
+ (dict(LanguageTable=None), {}, '[xyz](LanguageTable#cldf:l1)', 'xyz', None),
10
+ ({}, {}, '[xyz](LanguageTable#cldf:l1)', 'The Language', None),
11
+ ({}, {}, '[xyz](LanguageTable?_anchor=abc#cldf:l1)', '#abc', None),
12
+ ({}, {}, '[xyz](LanguageTable?ids=l1,l2,l3#cldf:__all__)', ' and ', None),
13
+ ({}, {}, '[xyz](ExampleTable#cldf:s1)', 'A sentence', None),
14
+ ({}, {}, '[xyz](ExampleTable?as_link#cldf:s1)', 'href=', None),
15
+ ({}, {}, '[xyz](ExampleTable?ids=s1#cldf:__all__)', '', None),
16
+ ({}, {}, '[xyz](NopeTable#cldf:1)', 'NopeTable', None),
17
+ (
18
+ {},
19
+ {},
20
+ '[](Source#cldf:Meier2012)\n[](Source?cited_only#cldf:__all__)',
21
+ 'Meier',
22
+ 'Mueller'),
23
+ ({}, {}, '[xyz](http://example.org)', 'http://example.org', None),
24
+ ]
25
+ )
26
+ def test_markdown(model_map, renderer_map, md, substring, notsubstring, dbsession, req_factory):
27
+ res = markdown(
28
+ req_factory(dict(model_map=model_map, renderer_map=renderer_map)), md, session=dbsession)
29
+ assert substring in res
30
+ if notsubstring:
31
+ assert notsubstring not in res
32
+
33
+
34
+ def test_markdown_keep_labels(dbsession, req_factory):
35
+ res = markdown(req_factory(), '[xyz](LanguageTable#cldf:l1)')
36
+ assert 'xyz' not in res
37
+ res = markdown(req_factory(dict(keep_link_labels=True)), '[xyz](LanguageTable#cldf:l1)')
38
+ assert 'xyz' in res