dochint 1.0.0__py3-none-any.whl
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.
- dochint/__init__.py +49 -0
- dochint/__main__.py +4 -0
- dochint/_cli.py +218 -0
- dochint/_helper.py +42 -0
- dochint/_macros.py +265 -0
- dochint/deferrable_string.py +41 -0
- dochint/exceptions.py +101 -0
- dochint/macro.py +141 -0
- dochint/processor.py +396 -0
- dochint/state.py +162 -0
- dochint-1.0.0.dist-info/METADATA +262 -0
- dochint-1.0.0.dist-info/RECORD +18 -0
- dochint-1.0.0.dist-info/WHEEL +5 -0
- dochint-1.0.0.dist-info/entry_points.txt +2 -0
- dochint-1.0.0.dist-info/licenses/LICENSE +1 -0
- dochint-1.0.0.dist-info/licenses/LICENSE.Apache-2.0 +202 -0
- dochint-1.0.0.dist-info/licenses/LICENSE.CC-BY-4.0 +396 -0
- dochint-1.0.0.dist-info/top_level.txt +1 -0
dochint/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'''A macro processor for authoring HTML documents.
|
|
2
|
+
|
|
3
|
+
The main entry points for this package are the process_text and process_texts
|
|
4
|
+
functions. The remainder of the Python API is used to define custom macros;
|
|
5
|
+
see Macro for more information. There is also a command-line interface to
|
|
6
|
+
dochint; see the README for more information.
|
|
7
|
+
|
|
8
|
+
For information about the behaviour of dochint, including how macro processing
|
|
9
|
+
works and which macros are available, see the README; such information is
|
|
10
|
+
beyond the scope of this package's docstrings.
|
|
11
|
+
'''
|
|
12
|
+
|
|
13
|
+
from .deferrable_string import DeferrableString, deferred_string_prefix
|
|
14
|
+
from .exceptions import (MacroCommandError,
|
|
15
|
+
MacroEmptyError,
|
|
16
|
+
IncompleteMacroError,
|
|
17
|
+
LaTeXMathsError,
|
|
18
|
+
LaTeXMathError,
|
|
19
|
+
CrossrefNotFoundError,
|
|
20
|
+
CrossrefExistsError,
|
|
21
|
+
CitationError,
|
|
22
|
+
BibTeXError,
|
|
23
|
+
FootnoteError)
|
|
24
|
+
from .macro import (ArgsMacroFunction,
|
|
25
|
+
RawMacroFunction,
|
|
26
|
+
ArgsMacro,
|
|
27
|
+
RawMacro,
|
|
28
|
+
Macro)
|
|
29
|
+
from .state import State
|
|
30
|
+
from .processor import process_text, process_texts
|
|
31
|
+
|
|
32
|
+
__all__ = ['DeferrableString', 'deferred_string_prefix',
|
|
33
|
+
'MacroCommandError',
|
|
34
|
+
'MacroEmptyError',
|
|
35
|
+
'IncompleteMacroError',
|
|
36
|
+
'LaTeXMathsError',
|
|
37
|
+
'LaTeXMathError',
|
|
38
|
+
'CrossrefNotFoundError',
|
|
39
|
+
'CrossrefExistsError',
|
|
40
|
+
'CitationError',
|
|
41
|
+
'BibTeXError',
|
|
42
|
+
'FootnoteError',
|
|
43
|
+
'ArgsMacroFunction',
|
|
44
|
+
'RawMacroFunction',
|
|
45
|
+
'ArgsMacro',
|
|
46
|
+
'RawMacro',
|
|
47
|
+
'Macro',
|
|
48
|
+
'State',
|
|
49
|
+
'process_text', 'process_texts']
|
dochint/__main__.py
ADDED
dochint/_cli.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
from . import exceptions, processor
|
|
2
|
+
import argparse
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
prog = os.path.basename(sys.argv[0])
|
|
6
|
+
|
|
7
|
+
def get_and_validate_args():
|
|
8
|
+
parser = argparse.ArgumentParser(prog=prog, usage=(f'{prog} [-h|--help] '
|
|
9
|
+
+'NAME... [OPTIONS...]'))
|
|
10
|
+
parser.add_argument('name', type=str, nargs='+', metavar='NAME',
|
|
11
|
+
help='Input file names.')
|
|
12
|
+
parser.add_argument('--output', '-o', type=str,
|
|
13
|
+
help=('Output file (if input is single file) or directory (if input '
|
|
14
|
+
+'is multiple files and --output-single-file is not set).'))
|
|
15
|
+
parser.add_argument('--output-single-file', action='store_true',
|
|
16
|
+
help='Output a single file for multi-file input.')
|
|
17
|
+
parser.add_argument('--source-dir', '--src-dir', '-d',
|
|
18
|
+
type=str, default='.',
|
|
19
|
+
help='Directory to look for input files in.')
|
|
20
|
+
parser.add_argument('--set-numbering', '-n', type=str, nargs=2,
|
|
21
|
+
action='append', metavar=('NAME', 'NUMBERING'), default=[],
|
|
22
|
+
help='Set the chapter numbering (or lettering) for a file.')
|
|
23
|
+
parser.add_argument('--prefix', '-p', type=str, default='\\',
|
|
24
|
+
help='Prefix for macro commands.')
|
|
25
|
+
parser.add_argument('--text-macro', '-t', type=str, nargs=2,
|
|
26
|
+
action='append', metavar=('MACRO', 'TO_TEXT'), default=[],
|
|
27
|
+
help='Define an extra text macro. Can be used multiple times.')
|
|
28
|
+
|
|
29
|
+
args = parser.parse_args()
|
|
30
|
+
|
|
31
|
+
# make sure input files exist
|
|
32
|
+
|
|
33
|
+
for name in args.name:
|
|
34
|
+
fpath = f'{args.source_dir}/{name}'
|
|
35
|
+
if not os.path.isfile(fpath):
|
|
36
|
+
print(f'{prog}: error: file \'{fpath}\' does not exist.',
|
|
37
|
+
file=sys.stderr)
|
|
38
|
+
exit(-1)
|
|
39
|
+
|
|
40
|
+
# make sure output destination is valid
|
|
41
|
+
|
|
42
|
+
if args.output is not None:
|
|
43
|
+
if len(args.name) == 1 or args.output_single_file:
|
|
44
|
+
output_dir = os.path.dirname(args.output)
|
|
45
|
+
output_dir = '.' if output_dir=='' else output_dir
|
|
46
|
+
if not os.path.isdir(output_dir):
|
|
47
|
+
print((f'{prog}: error: output directory \'{output_dir}\' '
|
|
48
|
+
+'does not exist.'), file=sys.stderr)
|
|
49
|
+
exit(-1)
|
|
50
|
+
else: # len(args.name) > 1 and not args.output_single_file
|
|
51
|
+
if not os.path.isdir(args.output):
|
|
52
|
+
print((f'{prog}: error: output directory \'{args.output}\' '
|
|
53
|
+
+'does not exist.'), file=sys.stderr)
|
|
54
|
+
exit(-1)
|
|
55
|
+
|
|
56
|
+
output_normpath = os.path.normpath(args.output)
|
|
57
|
+
source_normpath = os.path.normpath(args.source_dir)
|
|
58
|
+
if output_normpath == source_normpath:
|
|
59
|
+
print((f'{prog}: error: output directory \'{args.output}\' '
|
|
60
|
+
+'cannot be the same as --source-dir.'),
|
|
61
|
+
file=sys.stderr)
|
|
62
|
+
exit(-1)
|
|
63
|
+
else: # args.output is None
|
|
64
|
+
if len(args.name) > 1:
|
|
65
|
+
print((f'{prog}: error: cannot output multiple files to STDOUT '
|
|
66
|
+
+'unless --output-single-file is set.'), file=sys.stderr)
|
|
67
|
+
exit(-1)
|
|
68
|
+
|
|
69
|
+
# raise warning if --output-single-file set for single-file input
|
|
70
|
+
|
|
71
|
+
if len(args.name) == 1 and args.output_single_file:
|
|
72
|
+
print((f'{prog}: warning: --output-single-file '
|
|
73
|
+
+'is ignored for single-file input.'), file=sys.stderr)
|
|
74
|
+
|
|
75
|
+
# make sure numberings/letterings are correct
|
|
76
|
+
|
|
77
|
+
if len(args.name) > 1:
|
|
78
|
+
for name, numbering in args.set_numbering:
|
|
79
|
+
if name not in args.name:
|
|
80
|
+
print(f'{prog}: error: \'{name}\' is not an input file name.',
|
|
81
|
+
file=sys.stderr)
|
|
82
|
+
exit(-1)
|
|
83
|
+
if not (numbering.isnumeric() or numbering.isalpha()):
|
|
84
|
+
print((f'{prog}: error: \'{numbering}\' '
|
|
85
|
+
+'is not a valid numbering.'), file=sys.stderr)
|
|
86
|
+
exit(-1)
|
|
87
|
+
else:
|
|
88
|
+
if len(args.set_numbering) > 0:
|
|
89
|
+
print((f'{prog}: warning: --set-numbering '
|
|
90
|
+
+'is ignored for single-file input.'), file=sys.stderr)
|
|
91
|
+
|
|
92
|
+
# args have been validated
|
|
93
|
+
|
|
94
|
+
return args
|
|
95
|
+
|
|
96
|
+
def read_with_error(fpath, mode='r'):
|
|
97
|
+
try:
|
|
98
|
+
with open(fpath, mode) as f:
|
|
99
|
+
result = f.read()
|
|
100
|
+
except OSError:
|
|
101
|
+
print(f'{prog}: error: failed to read file \'{fpath}\'.',
|
|
102
|
+
file=sys.stderr)
|
|
103
|
+
exit(-1)
|
|
104
|
+
return result
|
|
105
|
+
|
|
106
|
+
def write_with_error(fpath, data, mode='w'):
|
|
107
|
+
try:
|
|
108
|
+
with open(fpath, mode) as f:
|
|
109
|
+
f.write(data)
|
|
110
|
+
except OSError:
|
|
111
|
+
print(f'{prog}: error: failed to write file \'{fpath}\'.',
|
|
112
|
+
file=sys.stderr)
|
|
113
|
+
exit(-1)
|
|
114
|
+
|
|
115
|
+
def extra_macros_dict(macro_list):
|
|
116
|
+
macros = {}
|
|
117
|
+
for macro, text in macro_list:
|
|
118
|
+
macros[macro] = text
|
|
119
|
+
return macros
|
|
120
|
+
|
|
121
|
+
def process_text_or_texts(multiple, text_or_texts,
|
|
122
|
+
numberings, prefix, extra_macros, cwd):
|
|
123
|
+
try:
|
|
124
|
+
if multiple:
|
|
125
|
+
processed = processor.process_texts(text_or_texts,
|
|
126
|
+
numberings=numberings, prefix=prefix,
|
|
127
|
+
extra_macros=extra_macros, cwd=cwd)
|
|
128
|
+
else:
|
|
129
|
+
processed = processor.process_text(text_or_texts, prefix=prefix,
|
|
130
|
+
extra_macros=extra_macros, cwd=cwd)
|
|
131
|
+
except exceptions.MacroCommandError as e:
|
|
132
|
+
print(f'{prog}: error: invalid macro \'{prefix}{e.message}\'.',
|
|
133
|
+
file=sys.stderr)
|
|
134
|
+
exit(-1)
|
|
135
|
+
except exceptions.MacroEmptyError:
|
|
136
|
+
print(f'{prog}: error: file ends with macro prefix \'{prefix}\'.',
|
|
137
|
+
file=sys.stderr)
|
|
138
|
+
exit(-1)
|
|
139
|
+
except exceptions.IncompleteMacroError as e:
|
|
140
|
+
print(f'{prog}: error: incomplete macro \'{prefix}{e.message}\'.',
|
|
141
|
+
file=sys.stderr)
|
|
142
|
+
exit(-1)
|
|
143
|
+
except exceptions.LaTeXMathsError as e:
|
|
144
|
+
print(f'{prog}: error: invalid LaTeX maths notation ({e.message}).',
|
|
145
|
+
file=sys.stderr)
|
|
146
|
+
exit(-1)
|
|
147
|
+
except exceptions.CrossrefNotFoundError as e:
|
|
148
|
+
print(f'{prog}: error: {e.message}')
|
|
149
|
+
exit(-1)
|
|
150
|
+
except exceptions.CrossrefExistsError as e:
|
|
151
|
+
print(f'{prog}: error: {e.message}')
|
|
152
|
+
exit(-1)
|
|
153
|
+
except exceptions.CitationError as e:
|
|
154
|
+
print(f'{prog}: error: {e.message}')
|
|
155
|
+
exit(-1)
|
|
156
|
+
except exceptions.BibTeXError as e:
|
|
157
|
+
print(f'{prog}: error: invalid BibTeX input ({e.message}).',
|
|
158
|
+
file=sys.stderr)
|
|
159
|
+
exit(-1)
|
|
160
|
+
except exceptions.FootnoteError as e:
|
|
161
|
+
print((f'{prog}: error: footnote set but never printed '
|
|
162
|
+
+f'({e.message}).'), file=sys.stderr)
|
|
163
|
+
exit(-1)
|
|
164
|
+
|
|
165
|
+
return processed
|
|
166
|
+
|
|
167
|
+
def do_single_file(args):
|
|
168
|
+
name = args.name[0]
|
|
169
|
+
fpath = f'{args.source_dir}/{name}'
|
|
170
|
+
text = read_with_error(fpath)
|
|
171
|
+
extra_macros = extra_macros_dict(args.text_macro)
|
|
172
|
+
processed = process_text_or_texts(False, text,
|
|
173
|
+
None, args.prefix, extra_macros, args.source_dir)
|
|
174
|
+
|
|
175
|
+
if args.output is None:
|
|
176
|
+
sys.stdout.write(processed)
|
|
177
|
+
sys.stdout.flush()
|
|
178
|
+
else:
|
|
179
|
+
write_with_error(args.output, processed)
|
|
180
|
+
|
|
181
|
+
def get_input_texts(args):
|
|
182
|
+
input_texts = []
|
|
183
|
+
for name in args.name:
|
|
184
|
+
fpath = f'{args.source_dir}/{name}'
|
|
185
|
+
text = read_with_error(fpath)
|
|
186
|
+
input_texts.append((name, text))
|
|
187
|
+
return input_texts
|
|
188
|
+
|
|
189
|
+
def do_multiple_files(args):
|
|
190
|
+
input_texts = get_input_texts(args)
|
|
191
|
+
extra_macros = extra_macros_dict(args.text_macro)
|
|
192
|
+
numberings = {name: numbering for (name, numbering) in args.set_numbering}
|
|
193
|
+
processed_texts = process_text_or_texts(True, input_texts,
|
|
194
|
+
numberings, args.prefix, extra_macros, args.source_dir)
|
|
195
|
+
|
|
196
|
+
if args.output is None: # and args.output_single_file
|
|
197
|
+
for name, text in processed_texts.items():
|
|
198
|
+
sys.stdout.write(text)
|
|
199
|
+
sys.stdout.flush()
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
if args.output_single_file:
|
|
203
|
+
concatenated_text = ''
|
|
204
|
+
for name in args.name:
|
|
205
|
+
text = processed_texts[name]
|
|
206
|
+
concatenated_text += text
|
|
207
|
+
write_with_error(args.output, concatenated_text)
|
|
208
|
+
else:
|
|
209
|
+
for name, text in processed_texts.items():
|
|
210
|
+
output_fpath = f'{args.output}/{name}'
|
|
211
|
+
write_with_error(output_fpath, text)
|
|
212
|
+
|
|
213
|
+
def main():
|
|
214
|
+
args = get_and_validate_args()
|
|
215
|
+
if len(args.name) == 1:
|
|
216
|
+
do_single_file(args)
|
|
217
|
+
else:
|
|
218
|
+
do_multiple_files(args)
|
dochint/_helper.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import html
|
|
2
|
+
import re
|
|
3
|
+
from xml.sax.saxutils import quoteattr
|
|
4
|
+
|
|
5
|
+
def href(id, current_fname, dest_fname):
|
|
6
|
+
if (dest_fname is None) or (current_fname == dest_fname):
|
|
7
|
+
return quoteattr(f'#{id}')
|
|
8
|
+
else:
|
|
9
|
+
return quoteattr(f'{dest_fname}#{id}')
|
|
10
|
+
|
|
11
|
+
def numbered_character_entities(text):
|
|
12
|
+
def numbered_entity_repl(named_entity_match):
|
|
13
|
+
named_entity = named_entity_match.group()
|
|
14
|
+
entity_str = html.unescape(named_entity)
|
|
15
|
+
result = ''
|
|
16
|
+
for c in entity_str:
|
|
17
|
+
result += f'&#{ord(c)};'
|
|
18
|
+
return result
|
|
19
|
+
|
|
20
|
+
return re.sub('&[^;]*;', numbered_entity_repl, text)
|
|
21
|
+
|
|
22
|
+
def base26_to_int(b26):
|
|
23
|
+
b26_lower = b26.lower()
|
|
24
|
+
result = 0
|
|
25
|
+
for c in b26_lower:
|
|
26
|
+
c_value = ord(c) - ord('a') + 1
|
|
27
|
+
if not 1 <= c_value <= 26:
|
|
28
|
+
raise ValueError(f'Invalid base 26 string `{b26}`')
|
|
29
|
+
result *= 26
|
|
30
|
+
result += c_value
|
|
31
|
+
return result
|
|
32
|
+
|
|
33
|
+
def int_to_base26(n):
|
|
34
|
+
result = ''
|
|
35
|
+
while n > 0:
|
|
36
|
+
i = n % 26
|
|
37
|
+
if i == 0:
|
|
38
|
+
i = 26
|
|
39
|
+
n -= i
|
|
40
|
+
n //= 26
|
|
41
|
+
result = chr(i + ord('A') - 1) + result
|
|
42
|
+
return result
|
dochint/_macros.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
from . import exceptions, deferrable_string, _helper
|
|
2
|
+
from .deferrable_string import DeferrableString
|
|
3
|
+
from .state import State
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
from typing import Any, Callable, Dict, Tuple
|
|
7
|
+
from xml.sax.saxutils import quoteattr
|
|
8
|
+
import latex2mathml.converter
|
|
9
|
+
import pybtex
|
|
10
|
+
import pybtex.database
|
|
11
|
+
|
|
12
|
+
def verbatim_func(text: str, **kwargs) -> [str, int]:
|
|
13
|
+
if len(text) == 0:
|
|
14
|
+
raise exceptions.IncompleteMacroError(
|
|
15
|
+
'Could not find opening delimiter.')
|
|
16
|
+
|
|
17
|
+
if len(text) == 1:
|
|
18
|
+
raise exceptions.IncompleteMacroError(
|
|
19
|
+
'Could not find closing delimiter')
|
|
20
|
+
|
|
21
|
+
delimiter = text[0]
|
|
22
|
+
text = text[1:]
|
|
23
|
+
len_consumed = 1
|
|
24
|
+
|
|
25
|
+
end = text.find(delimiter)
|
|
26
|
+
if end < 0:
|
|
27
|
+
raise exceptions.IncompleteMacroError(
|
|
28
|
+
'Could not find closing delimiter.')
|
|
29
|
+
|
|
30
|
+
verbatim_text = text[:end]
|
|
31
|
+
len_consumed += end + 1
|
|
32
|
+
|
|
33
|
+
escaped_text = html.escape(verbatim_text)
|
|
34
|
+
return escaped_text, len_consumed
|
|
35
|
+
|
|
36
|
+
def _math_core(latex: str, display: str) -> str:
|
|
37
|
+
try:
|
|
38
|
+
mathml = latex2mathml.converter.convert(latex, display=display)
|
|
39
|
+
except Exception as e:
|
|
40
|
+
raise exceptions.LaTeXMathsError(f'{type(e)}')
|
|
41
|
+
|
|
42
|
+
latex_escaped = quoteattr(latex)
|
|
43
|
+
i = len('<math ')
|
|
44
|
+
mathml = mathml[:i] + f'alttext={latex_escaped} ' + mathml[i:]
|
|
45
|
+
return mathml
|
|
46
|
+
|
|
47
|
+
def imath_func(latex: str, **kwargs) -> str:
|
|
48
|
+
return _math_core(latex, 'inline')
|
|
49
|
+
|
|
50
|
+
def dmath_func(latex: str, **kwargs) -> str:
|
|
51
|
+
return _math_core(latex, 'block')
|
|
52
|
+
|
|
53
|
+
def equation_func(id: str, latex: str, state: State, opts: list[str]) -> str:
|
|
54
|
+
if len(opts) > 0:
|
|
55
|
+
text = opts[0]
|
|
56
|
+
state.set_crossref(id, text=text)
|
|
57
|
+
else:
|
|
58
|
+
state.set_crossref(id)
|
|
59
|
+
text = state.get_crossref_text(id)
|
|
60
|
+
|
|
61
|
+
fig = f'<figure class=\'equation\' id={quoteattr(id)}>'
|
|
62
|
+
fig += _math_core(latex, 'block')
|
|
63
|
+
fig += f'<figcaption>({text})</figcaption>'
|
|
64
|
+
fig += '</figure>'
|
|
65
|
+
return fig
|
|
66
|
+
|
|
67
|
+
def id_func(id: str, state: State, opts: list[str]) -> str:
|
|
68
|
+
if len(opts) > 0:
|
|
69
|
+
text = opts[0]
|
|
70
|
+
state.set_crossref(id, text=text)
|
|
71
|
+
else:
|
|
72
|
+
state.set_crossref(id)
|
|
73
|
+
|
|
74
|
+
return quoteattr(id)
|
|
75
|
+
|
|
76
|
+
def tref_func(id: str, state: State, opts: list[str]) -> DeferrableString:
|
|
77
|
+
def deferred_str_func(state: State) -> str:
|
|
78
|
+
return state.get_crossref_text(id)
|
|
79
|
+
|
|
80
|
+
if state.contains_crossref(id):
|
|
81
|
+
return deferred_str_func(state)
|
|
82
|
+
else:
|
|
83
|
+
return deferred_str_func
|
|
84
|
+
|
|
85
|
+
def ref_func(id: str, state: State, opts: list[str]) -> DeferrableString:
|
|
86
|
+
filename = state.filename
|
|
87
|
+
|
|
88
|
+
def deferred_str_func(state: State) -> str:
|
|
89
|
+
return state.get_crossref_anchor(id)
|
|
90
|
+
|
|
91
|
+
if state.contains_crossref(id):
|
|
92
|
+
return deferred_str_func(state)
|
|
93
|
+
else:
|
|
94
|
+
return deferred_str_func
|
|
95
|
+
|
|
96
|
+
class _BibliographyState:
|
|
97
|
+
def __init__(self):
|
|
98
|
+
self.citation_order: Dict[str, int] = dict()
|
|
99
|
+
self.bibliography_items: Dict[str, str] = dict()
|
|
100
|
+
self.bibtex_data: list[pybtex.database.BibliographyData, str] = []
|
|
101
|
+
self.bibliography_present: bool = False
|
|
102
|
+
self.bibliography_filename: str = None
|
|
103
|
+
self.have_generated_bibliography: bool = False
|
|
104
|
+
|
|
105
|
+
def _get_or_init(state: State, attr: str, init_func: Callable) -> Any:
|
|
106
|
+
if attr not in state:
|
|
107
|
+
obj = init_func()
|
|
108
|
+
state[attr] = obj
|
|
109
|
+
return obj
|
|
110
|
+
else:
|
|
111
|
+
return state[attr]
|
|
112
|
+
|
|
113
|
+
def cite_func(ids: str, state: State, **kwargs) -> DeferrableString:
|
|
114
|
+
bib_state = _get_or_init(state, '_bibliography', _BibliographyState)
|
|
115
|
+
|
|
116
|
+
filename = state.filename
|
|
117
|
+
id_list = ids.split(',')
|
|
118
|
+
for id in id_list:
|
|
119
|
+
if id in bib_state.citation_order:
|
|
120
|
+
continue
|
|
121
|
+
index = len(bib_state.citation_order)
|
|
122
|
+
bib_state.citation_order[id] = index
|
|
123
|
+
|
|
124
|
+
def deferred_str_func(state: State) -> str:
|
|
125
|
+
bib_state = state['_bibliography']
|
|
126
|
+
if not bib_state.bibliography_present:
|
|
127
|
+
raise exceptions.CitationError(
|
|
128
|
+
'Citations present but no bibliography')
|
|
129
|
+
|
|
130
|
+
links = dict()
|
|
131
|
+
for id in id_list:
|
|
132
|
+
index = bib_state.citation_order[id]
|
|
133
|
+
href = _helper.href(id, filename, bib_state.bibliography_filename)
|
|
134
|
+
link = f'<a href={href}>{index+1}</a>'
|
|
135
|
+
links[link] = index
|
|
136
|
+
sorted_links = sorted(links, key=links.get)
|
|
137
|
+
citation = f'[{','.join(sorted_links)}]'
|
|
138
|
+
return citation
|
|
139
|
+
|
|
140
|
+
return deferred_str_func
|
|
141
|
+
|
|
142
|
+
def addbibitem_func(id: str, bib: str, state: State, **kwargs) -> str:
|
|
143
|
+
bib_state = _get_or_init(state, '_bibliography', _BibliographyState)
|
|
144
|
+
bib_state.bibliography_items[id] = bib
|
|
145
|
+
return ''
|
|
146
|
+
|
|
147
|
+
def addbibtextext_func(bibtex: str, state: State,**kwargs) -> str:
|
|
148
|
+
try:
|
|
149
|
+
db = pybtex.database.parse_string(bibtex, 'bibtex')
|
|
150
|
+
except Exception as e:
|
|
151
|
+
raise exceptions.BibTeXError(f'{type(e)}')
|
|
152
|
+
|
|
153
|
+
bib_state = _get_or_init(state, '_bibliography', _BibliographyState)
|
|
154
|
+
bib_state.bibtex_data.append((db, bibtex))
|
|
155
|
+
return ''
|
|
156
|
+
|
|
157
|
+
def addbibtexfile_func(bibtex_fpath: str, state: State,
|
|
158
|
+
**kwargs) -> DeferrableString:
|
|
159
|
+
if state.cwd is not None:
|
|
160
|
+
bibtex_fpath_full = f'{state.cwd}/{bibtex_fpath}'
|
|
161
|
+
else:
|
|
162
|
+
bibtex_fpath_full = bibtex_fpath
|
|
163
|
+
|
|
164
|
+
with open(bibtex_fpath_full, 'r') as f:
|
|
165
|
+
bibtex = f.read()
|
|
166
|
+
return addbibtextext_func(bibtex, state)
|
|
167
|
+
|
|
168
|
+
def _get_bibliography_html(bib_state: _BibliographyState) -> str:
|
|
169
|
+
bib_items = bib_state.bibliography_items
|
|
170
|
+
for db, bibtex in bib_state.bibtex_data:
|
|
171
|
+
db_ids = [id for id in db.entries
|
|
172
|
+
if id in bib_state.citation_order and id not in bib_items]
|
|
173
|
+
try:
|
|
174
|
+
citations_full_html_raw = pybtex.format_from_string(bibtex,
|
|
175
|
+
'unsrt', citations=db_ids, output_backend='html')
|
|
176
|
+
except Exception as e:
|
|
177
|
+
raise exceptions.BibTeXError(f'{type(e)}')
|
|
178
|
+
|
|
179
|
+
citations_full_html = _helper.numbered_character_entities(
|
|
180
|
+
citations_full_html_raw)
|
|
181
|
+
|
|
182
|
+
# extract citations inside <dd> elements
|
|
183
|
+
for id in db_ids:
|
|
184
|
+
l = '<dd>'
|
|
185
|
+
r = '</dd>'
|
|
186
|
+
j = citations_full_html.find(l) + len(l)
|
|
187
|
+
k = citations_full_html.find(r)
|
|
188
|
+
bib_items[id] = citations_full_html[j:k]
|
|
189
|
+
citations_full_html = citations_full_html[k+len(r):]
|
|
190
|
+
|
|
191
|
+
sorted_ids = sorted(bib_state.citation_order.keys(),
|
|
192
|
+
key=bib_state.citation_order.get)
|
|
193
|
+
|
|
194
|
+
html = '<ol>\n'
|
|
195
|
+
for id in sorted_ids:
|
|
196
|
+
if id not in bib_items:
|
|
197
|
+
raise exceptions.CitationError(
|
|
198
|
+
f'Bibliography item {id} does not exist')
|
|
199
|
+
|
|
200
|
+
# only add IDs to the list items in the first bibliography generated
|
|
201
|
+
if bib_state.have_generated_bibliography:
|
|
202
|
+
html += f'<li>{bib_items[id]}</li>\n'
|
|
203
|
+
else:
|
|
204
|
+
html += f'<li id={quoteattr(id)}>{bib_items[id]}</li>\n'
|
|
205
|
+
|
|
206
|
+
html += '</ol>'
|
|
207
|
+
bib_state.have_generated_bibliography = True
|
|
208
|
+
return html
|
|
209
|
+
|
|
210
|
+
def bibliography_func(state: State, **kwargs) -> DeferrableString:
|
|
211
|
+
def deferred_str_func(state: State) -> str:
|
|
212
|
+
bib_state = state['_bibliography']
|
|
213
|
+
return _get_bibliography_html(bib_state)
|
|
214
|
+
|
|
215
|
+
bib_state = _get_or_init(state, '_bibliography', _BibliographyState)
|
|
216
|
+
bib_state.bibliography_present = True
|
|
217
|
+
bib_state.bibliography_filename = state.filename
|
|
218
|
+
return deferred_str_func
|
|
219
|
+
|
|
220
|
+
class _FootnoteState:
|
|
221
|
+
def __init__(self):
|
|
222
|
+
self.footnote_groups: list[Tuple(str, Dict[str, Tuple[str, str]])] = []
|
|
223
|
+
self.pending_footnotes: list[str] = []
|
|
224
|
+
|
|
225
|
+
def footnote_func(text: str, state: State, **kwargs) -> DeferrableString:
|
|
226
|
+
footnote_state = _get_or_init(state, '_footnotes', _FootnoteState)
|
|
227
|
+
group_index = len(footnote_state.footnote_groups)
|
|
228
|
+
footnote_state.pending_footnotes.append(text)
|
|
229
|
+
|
|
230
|
+
def deferred_str_func(state: State) -> str:
|
|
231
|
+
footnote_state = state['_footnotes']
|
|
232
|
+
|
|
233
|
+
try:
|
|
234
|
+
footnote_group = footnote_state.footnote_groups[group_index]
|
|
235
|
+
except IndexError:
|
|
236
|
+
m = deferrable_string._replace_deferred_strings_with_ellipsis(text)
|
|
237
|
+
raise exceptions.FootnoteError(m)
|
|
238
|
+
|
|
239
|
+
group_filename, footnote_dict = footnote_group
|
|
240
|
+
id, ref_text = footnote_dict[text]
|
|
241
|
+
href = _helper.href(id, state.filename, group_filename)
|
|
242
|
+
return f'<sup><a href={href}>{ref_text}</a></sup>'
|
|
243
|
+
|
|
244
|
+
return deferred_str_func
|
|
245
|
+
|
|
246
|
+
def footnotes_func(state: State, **kwargs) -> str:
|
|
247
|
+
footnote_state = _get_or_init(state, '_footnotes', _FootnoteState)
|
|
248
|
+
group_index = len(footnote_state.footnote_groups)
|
|
249
|
+
footnote_texts = footnote_state.pending_footnotes
|
|
250
|
+
footnote_state.pending_footnotes = []
|
|
251
|
+
|
|
252
|
+
footnote_dict = dict()
|
|
253
|
+
footnote_htmls = []
|
|
254
|
+
for footnote_index, text in enumerate(footnote_texts):
|
|
255
|
+
ref_text = f'{footnote_index+1}'
|
|
256
|
+
id = f'_footnote_{group_index+1}_{footnote_index+1}'
|
|
257
|
+
footnote_dict[text] = (id, ref_text)
|
|
258
|
+
|
|
259
|
+
qid = quoteattr(id)
|
|
260
|
+
footnote_html = f'<p id={qid}><sup>{ref_text}</sup>{text}</p>'
|
|
261
|
+
footnote_htmls.append(footnote_html)
|
|
262
|
+
|
|
263
|
+
footnote_state.footnote_groups.append((state.filename, footnote_dict))
|
|
264
|
+
footnotes_html = '\n'.join(footnote_htmls)
|
|
265
|
+
return footnotes_html
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from .state import State
|
|
2
|
+
import re
|
|
3
|
+
from typing import Callable, TypeAlias, Union
|
|
4
|
+
|
|
5
|
+
DeferrableString: TypeAlias = Union[str, Callable[State, str]]
|
|
6
|
+
|
|
7
|
+
deferred_string_prefix = '\uedef'
|
|
8
|
+
|
|
9
|
+
def _escape_deferred_prefix(text: str) -> str:
|
|
10
|
+
return re.sub(re.escape(deferred_string_prefix),
|
|
11
|
+
f'{deferred_string_prefix};', text)
|
|
12
|
+
|
|
13
|
+
def _resolve_deferred_strings(text: str, ls: list[DeferrableString],
|
|
14
|
+
state: State) -> str:
|
|
15
|
+
pattern = f'{re.escape(deferred_string_prefix)}([0-9]*);'
|
|
16
|
+
def repl(match) -> str:
|
|
17
|
+
i_str = match.group(1)
|
|
18
|
+
if not i_str.isnumeric():
|
|
19
|
+
return deferred_string_prefix
|
|
20
|
+
|
|
21
|
+
i = int(i_str)
|
|
22
|
+
s = ls[i]
|
|
23
|
+
if isinstance(s, str):
|
|
24
|
+
return s
|
|
25
|
+
else:
|
|
26
|
+
s_resolved = _resolve_deferred_strings(s(state), ls, state)
|
|
27
|
+
ls[i] = s_resolved
|
|
28
|
+
return s_resolved
|
|
29
|
+
|
|
30
|
+
return re.sub(pattern, repl, text)
|
|
31
|
+
|
|
32
|
+
def _replace_deferred_strings_with_ellipsis(text: str) -> str:
|
|
33
|
+
pattern = f'{re.escape(deferred_string_prefix)}([0-9]*);'
|
|
34
|
+
def repl(match) -> str:
|
|
35
|
+
i_str = match.group(1)
|
|
36
|
+
if i_str.isnumeric():
|
|
37
|
+
return '...'
|
|
38
|
+
else:
|
|
39
|
+
return deferred_string_prefix
|
|
40
|
+
|
|
41
|
+
return re.sub(pattern, repl, text)
|