nextguidefmt 2.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.
nextguidefmt/node.py ADDED
@@ -0,0 +1,433 @@
1
+ # nextguidefmt/node.py
2
+
3
+ # Nodes are pages in NextGuide.
4
+
5
+
6
+
7
+ import re
8
+
9
+ from .index import GuideIndex
10
+
11
+ from .token import (
12
+ LINK_RE,
13
+ LITERALLINE_RE,
14
+ TOKEN_RE,
15
+ renderstring,
16
+ rendertoken,
17
+ )
18
+
19
+
20
+
21
+ # --- constants ---
22
+
23
+
24
+
25
+ # maximum allowed length for node name
26
+
27
+ NODE_NAME_MAXLEN = 15
28
+
29
+
30
+ # maximum number of links allowed in a node
31
+
32
+ NODE_MAXLINKS = 255
33
+
34
+
35
+ # maximum rendered length for a single line in a formatted the output guide
36
+
37
+ LINE_MAXLEN = 80
38
+
39
+
40
+ # valid types of links from a node
41
+
42
+ _NODE_LINK_TYPES = ["prev", "next", "toc"]
43
+
44
+
45
+ # special text to use as the link for a node link to indicate it should
46
+ # be left blank (and avoid auto-filling a missing entry)
47
+
48
+ NODE_LINK_NONE = '-'
49
+
50
+
51
+
52
+ # --- classes ---
53
+
54
+
55
+
56
+ class GuideNode(object):
57
+ """Represents a node (page in a NextGuide document).
58
+ """
59
+
60
+
61
+ def __init__(self, name):
62
+ """Initialise a new node.
63
+ """
64
+
65
+ super().__init__()
66
+
67
+ # store the name
68
+ self.name = name
69
+
70
+ # initialise the list of lines in the node
71
+ self._lines = []
72
+
73
+ # initialise the links to other nodes (prev/next/toc)
74
+ self._links = {}
75
+
76
+ # initialise list of warnings encountered
77
+ self._warnings = []
78
+
79
+ # add a warning if the node name is over length
80
+ if len(self.name) > NODE_NAME_MAXLEN:
81
+ self.addwarning(f"name over maximum length ({NODE_NAME_MAXLEN})")
82
+
83
+
84
+ def __repr__(self):
85
+ return f"GuideNode(@{self.name})"
86
+
87
+
88
+ def setlink(self, type_, target):
89
+ """Unconditionally set the link to another node (prev/next/toc).
90
+ This is used when a node explicitly sets the link.
91
+ """
92
+
93
+ # check the link is of a valid type
94
+ if type_ not in _NODE_LINK_TYPES:
95
+ return ValueError(f"set invalid link type: {type_}")
96
+
97
+ self._links[type_] = target if target != NODE_LINK_NONE else None
98
+
99
+
100
+ def setdefaultlink(self, type_, target):
101
+ """Set the link to another node only if this link is not yet
102
+ defined. This used when the entire document is completed and
103
+ the missing links are filled in.
104
+ """
105
+
106
+ # check the link is of a valid type
107
+ if type_ not in _NODE_LINK_TYPES:
108
+ return ValueError(f"set default invalid link type: {type_}")
109
+
110
+ if target:
111
+ self._links.setdefault(type_, target)
112
+
113
+
114
+ def getlink(self, type_):
115
+ """Return the link to the specified target from this node, or
116
+ None, if it is not defined.
117
+ """
118
+
119
+ # check the link is of a valid type
120
+ if type_ not in _NODE_LINK_TYPES:
121
+ return ValueError(f"get invalid link type: {type_}")
122
+
123
+ return self._links.get(type_)
124
+
125
+
126
+ def addwarning(self, warning):
127
+ """Add a warning to the list of warnings about this node.
128
+ """
129
+
130
+ self._warnings.append(warning)
131
+
132
+
133
+ def getwarnings(self):
134
+ """Return the list of warnings about this node.
135
+ """
136
+
137
+ return self._warnings
138
+
139
+
140
+ def appendline(self, l):
141
+ """Add a line to the current node.
142
+ """
143
+
144
+ self._lines.append(l)
145
+
146
+
147
+ def replacelines(self, lines):
148
+ """Replace all the lines in the body of a node with a new set.
149
+ """
150
+
151
+ self._lines = lines
152
+
153
+
154
+ def checklink(self, type_, node_names):
155
+ """Check the target of a particular node link type exists in the
156
+ supplied list of node names (from a document or set), returning
157
+ False iff it is defined and does not.
158
+
159
+ A warning will also be recorded, if it does not.
160
+ """
161
+
162
+ link_name = self.getlink(type_)
163
+
164
+ # if link is defined and no node exists with that name,
165
+ # record a warning
166
+ exists = (not link_name) or (link_name in node_names)
167
+ if not exists:
168
+ self.addwarning(
169
+ f"link type: {type_} target: @{link_name} does not"
170
+ " exist")
171
+
172
+ return exists
173
+
174
+
175
+ def checklinks(self, node_names):
176
+ """Check all the node link types for this document exist in the
177
+ supplied list of node names (from a document or set). False
178
+ will be returned iff any are defined and are missing, as well as
179
+ warnings recorded.
180
+ """
181
+
182
+ all_exist = True
183
+ for link_type in _NODE_LINK_TYPES:
184
+ all_exist &= self.checklink(link_type, node_names)
185
+
186
+ return all_exist
187
+
188
+
189
+ def parseindex(self):
190
+ """Parse this node as an index, returning the GuideIndex()
191
+ object with all the terms and references.
192
+ """
193
+
194
+ index = GuideIndex()
195
+ index.parselines(self._lines)
196
+ return index
197
+
198
+
199
+ def format(self, *, doc, node_docs, line_maxlen, markup=True):
200
+ """Format the node for output, handling word wrap for the
201
+ specified maximum line length, and qualifying links with
202
+ document names, if required.
203
+
204
+ The 'doc' and 'node_docs' objects are required to fix up links
205
+ across documents in a set.
206
+
207
+ 'markup' specifies whether the returned data should contain
208
+ markup (True) or a plain text, readable version of the text
209
+ (False).
210
+
211
+ The output is returned as a list of lines as strings.
212
+ """
213
+
214
+
215
+ # the list of output lines to be returned, starting with the
216
+ # '@node' command, identifying the node, if we're using markup,
217
+ # or the empty list if not
218
+ output = ["@node " + self.name] if markup else []
219
+
220
+ # the current line being assembled - we store two versions:
221
+ #
222
+ # line_markup contains the text containing literal text and
223
+ # commands and is used for the actual output
224
+ line_markup = ""
225
+ #
226
+ # line_render contains the displayed text equivalent, obtained
227
+ # using rendertoken(), and is used to calculate displayed text
228
+ # lengths for wrapping words
229
+ line_render = ""
230
+
231
+ # the current 'word' being assembled - a word is a sequence of
232
+ # tokens (markup, literal text, etc.) that cannot be broken
233
+ # across lines - if it cannot fit on a line, a new line will be
234
+ # begun
235
+ word_markup = ""
236
+ word_render = ""
237
+
238
+ # any spaces before the current word - these will be discarded
239
+ # if the word wraps onto the next line
240
+ pre_space = ""
241
+
242
+ # if we're including markup, add the links to other documents
243
+ # (prev/next/toc) if they are defined for this node and they are
244
+ # not 'None' (which means explicitly not set)
245
+ if markup:
246
+ for link in _NODE_LINK_TYPES:
247
+ if (link in self._links) and self._links[link]:
248
+ output.append(f"@{link} {self._links[link]}")
249
+
250
+ # number of links encountered so far in the node - we use this
251
+ # to track if we have too many and need to raise a warning
252
+ num_links = 0
253
+
254
+
255
+ # --- subfunctions ---
256
+
257
+
258
+ def writeline():
259
+ """Add the line currently being assembled to the list of
260
+ output lines and start a new one.
261
+ """
262
+
263
+ nonlocal line_markup, line_render, pre_space
264
+
265
+ if line_markup:
266
+ output.append(line_markup if markup else line_render)
267
+
268
+ line_markup = ''
269
+ line_render = ''
270
+
271
+ # as we're starting a new line, we don't need the spaces
272
+ # that would separate the current word from the previous
273
+ # one
274
+ pre_space = ''
275
+
276
+
277
+ def completeword(space=''):
278
+ """Called when the current word being assembled has been
279
+ completed (by some space, or at the end of a document). It
280
+ will add the word to the end of the line, if it fits, or
281
+ start a new one with it.
282
+
283
+ The supplied 'space' is the separator between this complete
284
+ word and the next and is recorded in pre_space.
285
+ """
286
+
287
+ nonlocal line_markup, line_render, word_markup, word_render
288
+ nonlocal pre_space
289
+
290
+ # if no line or word is currently being assembled, we have
291
+ # nothing to do
292
+ if (not line_render) and (not word_render):
293
+ return
294
+
295
+ # check if adding the pre_space and word to the line would
296
+ # take it over the maximum length
297
+ if len(line_render + pre_space + word_render) > line_maxlen:
298
+ # line would be over maximum - write it out
299
+ writeline()
300
+
301
+ # discard the space, as we're beginning a new line
302
+
303
+ else:
304
+ # the word will fit on this line - add the separating
305
+ # pre_space
306
+ line_markup += pre_space
307
+ line_render += pre_space
308
+
309
+ # add the word to the line (either a new, empty one, or
310
+ # continuing the current one)
311
+ line_markup += word_markup
312
+ line_render += word_render
313
+
314
+ # start a new word
315
+ word_markup = ''
316
+ word_render = ''
317
+
318
+ # record the supplied space if required for the next word
319
+ pre_space = space
320
+
321
+
322
+ def appendtoken(token):
323
+ """Add the supplied token to the current word.
324
+
325
+ This will add the markup, if 'markup' is set, or the plain
326
+ text rendering, if not. If plain text is requested, links
327
+ will be 'bracketed' by rendertoken().
328
+ """
329
+
330
+ nonlocal word_markup, word_render
331
+
332
+ word_markup += token
333
+ word_render += rendertoken(token, link_bracket=not markup)
334
+
335
+
336
+ def fixlink_repl(m):
337
+ """Used as an argument to re.sub(repl) to fix up links, if
338
+ required; qualifying them with the document name, if they
339
+ are in a different document to the this node.
340
+
341
+ This function uses the 'doc' and 'node_docs' arguments to
342
+ the containing format() method.
343
+ """
344
+
345
+ text, target = m.group("link_text", "link_target")
346
+
347
+ # fix up the target - if not found in node_docs, None will
348
+ # be returned, indicating a broken link
349
+ fixed_target = node_docs.fixlink(doc, target)
350
+
351
+ # if the target was not found, record a warning
352
+ if fixed_target is None:
353
+ self.addwarning(
354
+ f"link: '{text}' target: @{target} does not exist")
355
+
356
+ # return the fixed link or, if the target was not found,
357
+ # return the target anyway
358
+ return '@{"' + text + '" LINK ' + (fixed_target or target) + '}'
359
+
360
+
361
+ # --- method ---
362
+
363
+
364
+ # go through the lines in this node
365
+ for line in self._lines:
366
+ # count the number of links in this line and add it to the
367
+ # total for this node
368
+ num_links += len(re.findall(LINK_RE, line))
369
+
370
+ # fix all the links in this line such that, if a link is to
371
+ # a node in another document in the set, qualify it by
372
+ # prefixing 'Document/'
373
+ #
374
+ # this will also record warnings on for link targets which
375
+ # don't exist
376
+ line = re.sub(LINK_RE, fixlink_repl, line)
377
+
378
+ # if the line is blank, or is one that is to be included
379
+ # literally, just add that to the document
380
+ if (line == '') or LITERALLINE_RE.match(line):
381
+ # finish the current line and append it (if it has
382
+ # something in it)
383
+ writeline()
384
+
385
+ # add the literal line - this will contain markup, if
386
+ # this is requested, or the rendered, plain text version
387
+ # with link 'bracketing' if not
388
+ output.append(
389
+ line if markup
390
+ else renderstring(line, link_bracket=not markup,
391
+ line_maxlen=line_maxlen))
392
+
393
+ continue
394
+
395
+ # go through the line matching tokens (markup, literal or spaces)
396
+ remainder = line
397
+ while remainder:
398
+ m = re.match(TOKEN_RE, remainder)
399
+
400
+ # if we couldn't match a token, something has gone
401
+ # irretrievably wrong (probably with the regexp)
402
+ if not m:
403
+ raise ValueError(
404
+ "failed to match next token in: " + remainder)
405
+
406
+ token, remainder = m.group("token", "remainder")
407
+
408
+ if m.group("space"):
409
+ # token is a space - complete the current word
410
+ completeword(space=token)
411
+ else:
412
+ # token is not a space - try to add it to the
413
+ # current line (otherwise begin a new one)
414
+ appendtoken(token)
415
+
416
+ # the end of line in the source text completes a word and
417
+ # adds a separating space before the next one (if there is
418
+ # one)
419
+ completeword(space=' ')
420
+
421
+ # we've finished the node, flush out anything assembled in the
422
+ # line buffer
423
+ writeline()
424
+
425
+ # if the number of links on this page exceed the maximum, add a
426
+ # a warning
427
+ if num_links > NODE_MAXLINKS:
428
+ self.addwarning(
429
+ f"number of links: {num_links} over maximum:"
430
+ f" {NODE_MAXLINKS} - excess links will be unselectable")
431
+
432
+ # return the list of formatted lines
433
+ return output