1
|
1
|
from collections import OrderedDict
|
2
|
1
|
import re
|
3
|
1
|
import os
|
4
|
1
|
from six import string_types
|
5
|
|
|
6
|
|
|
7
|
1
|
def strip_ext(path):
|
8
|
1
|
return os.path.splitext(path)[0]
|
9
|
|
|
10
|
|
|
11
|
1
|
def basename(path, ext=False):
|
12
|
1
|
basename = os.path.basename(path)
|
13
|
1
|
if not ext:
|
14
|
1
|
basename = os.path.splitext(basename)[0]
|
15
|
1
|
return basename
|
16
|
|
|
17
|
|
|
18
|
1
|
def get_empty_lines(text):
|
19
|
|
"""Get number of empty lines before and after text."""
|
20
|
1
|
before = len(text) - len(text.lstrip("\n"))
|
21
|
1
|
after = len(text) - len(text.strip("\n")) - before
|
22
|
1
|
return before, after
|
23
|
|
|
24
|
|
|
25
|
1
|
def wrap_latex(input, max_length=75, **kwargs):
|
26
|
0
|
if len(input) > max_length:
|
27
|
|
# remove double dollars, as they don't allow word wrap
|
28
|
0
|
if len(input) > 3:
|
29
|
0
|
if input[0:2] == "$$" and input[-2:] == "$$":
|
30
|
0
|
input = input[1:-1]
|
31
|
|
# change \left( and \right) to \bigg( and \bigg), as allow word wrap
|
32
|
0
|
input = input.replace(r"\left(", r"\big(")
|
33
|
0
|
input = input.replace(r"\right)", r"\big)")
|
34
|
|
|
35
|
0
|
return input
|
36
|
|
|
37
|
|
|
38
|
1
|
def remove_dollars(text):
|
39
|
|
"""remove dollars from start/end of text"""
|
40
|
1
|
while text.startswith("$"):
|
41
|
1
|
text = text[1:]
|
42
|
1
|
while text.endswith("$"):
|
43
|
1
|
text = text[0:-1]
|
44
|
1
|
return text
|
45
|
|
|
46
|
|
|
47
|
1
|
def wrap_eqn(text, cell_meta, nb_meta, out="latex"):
|
48
|
|
""" wrap an equation in a latex equation environment
|
49
|
|
|
50
|
|
environment obtained (if present) from cell_meta.ipub.equation.environment)
|
51
|
|
label obtained (if present) from cell_meta.ipub.equation.label)
|
52
|
|
also, nb_meta.ipub.enable_breqn used
|
53
|
|
|
54
|
|
Parameters
|
55
|
|
----------
|
56
|
|
text: str
|
57
|
|
cell_meta: dict
|
58
|
|
the cell metadata
|
59
|
|
nb_meta: dict
|
60
|
|
the notebook metadata
|
61
|
|
|
62
|
|
Returns
|
63
|
|
-------
|
64
|
|
new_text: str
|
65
|
|
|
66
|
|
"""
|
67
|
1
|
numbered = True
|
68
|
1
|
try:
|
69
|
1
|
environment = cell_meta["ipub"]["equation"]["environment"]
|
70
|
1
|
except (KeyError, TypeError):
|
71
|
1
|
environment = None
|
72
|
1
|
if environment == "none":
|
73
|
0
|
environment = None
|
74
|
1
|
elif environment in ["equation*", "align*", "multline*", "gather*", "eqnarray*"]:
|
75
|
0
|
numbered = False
|
76
|
1
|
elif environment in ["equation", "align", "multline", "gather", "eqnarray"]:
|
77
|
1
|
pass
|
78
|
1
|
elif environment == "breqn" and out == "latex":
|
79
|
0
|
if nb_meta.get("ipub", {}).get("enable_breqn", False):
|
80
|
0
|
environment = "dmath*"
|
81
|
|
else:
|
82
|
0
|
environment = None
|
83
|
|
else:
|
84
|
1
|
environment = None
|
85
|
|
|
86
|
1
|
try:
|
87
|
1
|
label = cell_meta["ipub"]["equation"]["label"]
|
88
|
0
|
except (KeyError, TypeError):
|
89
|
0
|
label = None
|
90
|
|
|
91
|
1
|
if environment:
|
92
|
1
|
outtext = "\\begin{{{0}}}".format(environment)
|
93
|
1
|
if label and numbered and out == "latex":
|
94
|
1
|
outtext += "\\label{{{0}}}".format(label)
|
95
|
1
|
outtext += "\n" + remove_dollars(text)
|
96
|
1
|
outtext += "\n\\end{{{0}}}".format(environment)
|
97
|
|
else:
|
98
|
1
|
outtext = text
|
99
|
|
|
100
|
1
|
return outtext
|
101
|
|
|
102
|
|
|
103
|
1
|
def get_caption(etype, cell_meta, resources):
|
104
|
|
"""return an ipypublish caption or False
|
105
|
|
|
106
|
|
captions can either be located at cell_meta.ipub.<type>.caption,
|
107
|
|
or at resources.caption[cell_meta.ipub.<type>.label]
|
108
|
|
|
109
|
|
the resources version is proritised
|
110
|
|
"""
|
111
|
1
|
try:
|
112
|
1
|
caption = cell_meta["ipub"][etype]["caption"]
|
113
|
1
|
except (KeyError, TypeError):
|
114
|
1
|
caption = False
|
115
|
|
|
116
|
1
|
try:
|
117
|
1
|
label = cell_meta["ipub"][etype]["label"]
|
118
|
1
|
except (KeyError, TypeError):
|
119
|
1
|
label = False
|
120
|
|
|
121
|
1
|
rcaption = False
|
122
|
1
|
if label:
|
123
|
1
|
try:
|
124
|
1
|
rcaption = resources["caption"][label]
|
125
|
1
|
except (KeyError, TypeError):
|
126
|
1
|
pass
|
127
|
|
|
128
|
1
|
if rcaption:
|
129
|
0
|
return rcaption
|
130
|
1
|
return caption
|
131
|
|
|
132
|
|
|
133
|
1
|
def first_para(input, **kwargs):
|
134
|
|
r"""get only ttext before a \n (i.e. the fist paragraph)"""
|
135
|
0
|
return input.split("\n")[0]
|
136
|
|
|
137
|
|
|
138
|
1
|
def _write_roman(num):
|
139
|
1
|
roman = OrderedDict()
|
140
|
1
|
roman[1000] = "M"
|
141
|
1
|
roman[900] = "CM"
|
142
|
1
|
roman[500] = "D"
|
143
|
1
|
roman[400] = "CD"
|
144
|
1
|
roman[100] = "C"
|
145
|
1
|
roman[90] = "XC"
|
146
|
1
|
roman[50] = "L"
|
147
|
1
|
roman[40] = "XL"
|
148
|
1
|
roman[10] = "X"
|
149
|
1
|
roman[9] = "IX"
|
150
|
1
|
roman[5] = "V"
|
151
|
1
|
roman[4] = "IV"
|
152
|
1
|
roman[1] = "I"
|
153
|
|
|
154
|
1
|
def roman_num(num):
|
155
|
1
|
for r in roman.keys():
|
156
|
1
|
x, y = divmod(num, r)
|
157
|
1
|
yield roman[r] * x
|
158
|
1
|
num -= r * x
|
159
|
1
|
if num > 0:
|
160
|
1
|
roman_num(num)
|
161
|
|
else:
|
162
|
1
|
break
|
163
|
|
|
164
|
1
|
return "".join([a for a in roman_num(num)])
|
165
|
|
|
166
|
|
|
167
|
1
|
def _repl(match):
|
168
|
1
|
return _write_roman(int(match.group(0)))
|
169
|
|
|
170
|
|
|
171
|
1
|
def create_key(input, **kwargs):
|
172
|
|
"""create sanitized key string which only contains lowercase letters,
|
173
|
|
(semi)colons as c, underscores as u and numbers as roman numerals
|
174
|
|
in this way the keys with different input should mainly be unique
|
175
|
|
|
176
|
|
>>> create_key('fig:A_10name56')
|
177
|
|
'figcauxnamelvi'
|
178
|
|
|
179
|
|
"""
|
180
|
1
|
input = re.compile(r"\d+").sub(_repl, input)
|
181
|
1
|
input = input.replace(":", "c")
|
182
|
1
|
input = input.replace(";", "c")
|
183
|
1
|
input = input.replace("_", "u")
|
184
|
1
|
return re.sub("[^a-zA-Z]+", "", str(input)).lower()
|
185
|
|
|
186
|
|
|
187
|
1
|
def _split_option(item, original):
|
188
|
1
|
opt = item.split("=")
|
189
|
1
|
if len(opt) > 2:
|
190
|
0
|
raise ValueError(
|
191
|
|
"item '{}' from '{}' contains multiple '='".format(item, original)
|
192
|
|
)
|
193
|
1
|
elif len(opt) == 1:
|
194
|
1
|
return opt[0].strip(), None
|
195
|
|
else:
|
196
|
1
|
return [o.strip() for o in opt]
|
197
|
|
|
198
|
|
|
199
|
1
|
def dict_to_kwds(inobject, kwdstr="", overwrite=True):
|
200
|
|
""" convert a dictionary to a string of keywords,
|
201
|
|
or, if a list, a string of options
|
202
|
|
|
203
|
|
append to an existing options string (without duplication)
|
204
|
|
|
205
|
|
Parameters
|
206
|
|
----------
|
207
|
|
dct : dict
|
208
|
|
kwdstr: str
|
209
|
|
initial keyword string
|
210
|
|
overwrite: bool
|
211
|
|
overwrite the option, if it already exists with a different value
|
212
|
|
|
213
|
|
Examples
|
214
|
|
--------
|
215
|
|
>>> dict_to_kwds({"a":1,"c":3},'a=1,b=2')
|
216
|
|
'a=1,b=2,c=3'
|
217
|
|
>>> dict_to_kwds(['a', 'c'],'a,b')
|
218
|
|
'a,b,c'
|
219
|
|
|
220
|
|
"""
|
221
|
1
|
if not isinstance(kwdstr, string_types):
|
222
|
0
|
raise ValueError("kwdstr '{}' not a string".format(kwdstr))
|
223
|
|
|
224
|
1
|
optdict = {}
|
225
|
1
|
for item in kwdstr.split(","):
|
226
|
1
|
if item == "":
|
227
|
1
|
continue
|
228
|
1
|
ikey, ival = _split_option(item, kwdstr)
|
229
|
1
|
if ikey in optdict:
|
230
|
0
|
raise ValueError(
|
231
|
|
"kwdstr '{}' contain multiple references to '{}'".format(kwdstr, ikey)
|
232
|
|
)
|
233
|
1
|
optdict[ikey] = ival
|
234
|
|
|
235
|
1
|
if isinstance(inobject, (list, tuple)):
|
236
|
1
|
for item in inobject:
|
237
|
1
|
if item == "":
|
238
|
0
|
continue
|
239
|
1
|
if not isinstance(item, string_types):
|
240
|
0
|
raise ValueError(
|
241
|
|
"option '{}' from option list is not a string: {}".format(
|
242
|
|
item, kwdstr
|
243
|
|
)
|
244
|
|
)
|
245
|
1
|
okey, oval = _split_option(item, inobject)
|
246
|
1
|
if okey not in optdict or overwrite:
|
247
|
1
|
optdict[okey] = oval
|
248
|
|
else:
|
249
|
1
|
for kkey in sorted(inobject.keys()):
|
250
|
1
|
keystr = str(kkey)
|
251
|
1
|
if keystr not in optdict or overwrite:
|
252
|
1
|
optdict[kkey] = str(inobject[kkey])
|
253
|
|
|
254
|
1
|
outstring1 = []
|
255
|
1
|
outstring2 = []
|
256
|
1
|
for skey in sorted(optdict.keys()):
|
257
|
1
|
if optdict[skey] is None:
|
258
|
1
|
outstring1.append(skey)
|
259
|
|
else:
|
260
|
1
|
outstring2.append("{}={}".format(skey, optdict[skey]))
|
261
|
|
|
262
|
1
|
outstring = outstring1 + outstring2
|
263
|
1
|
return ",".join(outstring)
|
264
|
|
|
265
|
|
|
266
|
1
|
def is_equation(text):
|
267
|
|
"""test if a piece of text is a latex equation, by how it is wrapped"""
|
268
|
1
|
text = text.strip()
|
269
|
|
|
270
|
1
|
if any(
|
271
|
|
[
|
272
|
|
text.startswith("\\begin{{{0}}}".format(env))
|
273
|
|
and text.endswith("\\end{{{0}}}".format(env))
|
274
|
|
for env in [
|
275
|
|
"equation",
|
276
|
|
"split",
|
277
|
|
"equation*",
|
278
|
|
"align",
|
279
|
|
"align*",
|
280
|
|
"multline",
|
281
|
|
"multline*",
|
282
|
|
"gather",
|
283
|
|
"gather*",
|
284
|
|
]
|
285
|
|
]
|
286
|
|
):
|
287
|
0
|
return True
|
288
|
1
|
elif text.startswith("$") and text.endswith("$"):
|
289
|
1
|
return True
|
290
|
|
else:
|
291
|
1
|
return False
|
292
|
|
|
293
|
|
|
294
|
1
|
if __name__ == "__main__":
|
295
|
|
|
296
|
0
|
print(dict_to_kwds(["a", "c"], "e,b,d=3"))
|