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/index.py ADDED
@@ -0,0 +1,733 @@
1
+ # nextguidefmt/index.py
2
+
3
+ # Classes for managing links between documents and indices.
4
+
5
+
6
+
7
+ import re
8
+
9
+ from .token import LINK_RESTR, renderstring
10
+
11
+
12
+
13
+ # --- constants ---
14
+
15
+
16
+
17
+ # default indent for the references (right) columnn in a formatted
18
+ # (generated) index - this is the width of the terms (left) column
19
+
20
+ DEFAULT_REFS_INDENT = 22
21
+
22
+
23
+ # minimum number of spaces to leave between a term and the start of the
24
+ # references for an index entry in a formatted index - if term width +
25
+ # refs gap is > refs indent (above), the references will start on the
26
+ # following line
27
+
28
+ DEFAULT_REFS_GAP = 3
29
+
30
+
31
+ # regular expressions for matching a line in a defined index page in a
32
+ # source file
33
+
34
+ # the first one matches the 'term' (the left column) and leaves the
35
+ # references as a remainder to be parsed by the second expression, below
36
+
37
+ INDEX_LINE_RE = re.compile(
38
+ # lines can begin with 0-2 spaces
39
+ r'\s{,2}'
40
+
41
+ # a line can have a 'term' (in the left hand column) which is a
42
+ # block of static text or a link
43
+ #
44
+ # if this is omitted, the term will be continued from the previous
45
+ # line (this is handled elsewhere)
46
+ + '('
47
+ + LINK_RESTR
48
+ + r"|(?P<static_text>\S+(\s{,2}\S+)*)"
49
+ + r")?"
50
+
51
+ # optionally followed by 3 or more spaces and a list of references
52
+ # as 'refs', which we parse separately, using the expression below
53
+ + r"(\s{3,}(?P<refs>.+))?")
54
+
55
+
56
+ # this regular expression matches references (the right column) one at a
57
+ # time from the 'remainder' column in the line expression, above
58
+
59
+ INDEX_REFS_RE = re.compile(
60
+ # the references column contains a link
61
+ LINK_RESTR
62
+
63
+ # the remainder (if present) is separately by a comma and optional
64
+ # space
65
+ + r"(,\s*(?P<remainder>.+))?")
66
+
67
+
68
+ # the separating character between the document name and node name in a
69
+ # link between documents
70
+
71
+ DOC_SEPARATOR = ':'
72
+
73
+
74
+
75
+ # --- functions ---
76
+
77
+
78
+
79
+ def indextermkey_factory(term_prefixes):
80
+ """Factory function to make a function which will return the sort
81
+ key to be used by a term in the index. The first character of this
82
+ string will also be used to group terms in the index.
83
+
84
+ The generated function will to be supplied to GuideIndex().
85
+
86
+ The function will use the following rules in order:
87
+
88
+ 1. If the term starts with one of the strings in the list
89
+ 'index_term_prefixes', that prefix will be removed and the rest
90
+ of the string used. This can be used to remove leading
91
+ characters and strings to be ignored when sorting the index.
92
+
93
+ 2. If the term starts with anything other than a number or letter,
94
+ a space will be prefixed, causing those terms to be grouped
95
+ together at the start (since space comes before all other
96
+ printable characters) but still appear sorted within that.
97
+
98
+ 3. Anything else is returned as is.
99
+
100
+ All returned terms will be lower-cased to remove case from the sort
101
+ criteria.
102
+ """
103
+
104
+ def indextermkey(term):
105
+ # if the term starts with one of the prefix strings, strip that
106
+ # off and return it lower-cased
107
+ for prefix in term_prefixes:
108
+ if term.startswith(prefix):
109
+ return term[len(prefix):].lower()
110
+
111
+ # if the term doesn't start with an alphanumeric character,
112
+ # prefix it with a space and lower-case it
113
+ if not re.match("[0-9A-Z]", term, re.IGNORECASE):
114
+ return ' ' + term.lower()
115
+
116
+ # return the term lower-cased
117
+ return term.lower()
118
+
119
+ # return the function
120
+ return indextermkey
121
+
122
+
123
+
124
+ def linkcmd(text, target):
125
+ """Generate a command for a link, given the specified text and a
126
+ target.
127
+ """
128
+
129
+ return '@{"' + text + '" LINK ' + target + '}'
130
+
131
+
132
+
133
+ def _itermore(iterable):
134
+ """Returns a generator yielding a tuple consisting of two values.
135
+ The first is the next iteration of the supplied iterable, and the
136
+ second is a boolean that indicates if there are more items available
137
+ in the iterable. The second value will be True for all iterations
138
+ except the last.
139
+ """
140
+
141
+ # get an iterator for the iterable
142
+ i = iter(iterable)
143
+
144
+ try:
145
+ # try to get the first item
146
+ item = next(i)
147
+
148
+ except StopIteration:
149
+ # it failed, we're done (with no items)
150
+ return
151
+
152
+ # iterate through the items in the iterable, starting with the
153
+ # second (as we got the first, above)
154
+ for next_ in i:
155
+ # return the item retrieved last time and True, to signal there
156
+ # are more items to come
157
+ yield item, True
158
+
159
+ # store the item we retreived this time to return next time
160
+ item = next_
161
+
162
+ # we've exhausted the iterable - return the item we got last time
163
+ # and False, to indicate there are no more items available
164
+ yield item, False
165
+
166
+ # no further items, so the generator will stop here
167
+
168
+
169
+
170
+ # --- classes ---
171
+
172
+
173
+
174
+ class GuideNodeDocs(object):
175
+ """Represents a mapping between a node name (held in the key of a
176
+ dict) and the document it's in. This is used to fix links to nodes
177
+ in other documents by prefixing them with the document name.
178
+ """
179
+
180
+
181
+ def __init__(self):
182
+ """Initialise a GuideNodeDocs object.
183
+ """
184
+
185
+ super().__init__()
186
+
187
+ # initialise the dictionary of nodes to be empty
188
+ self._nodes = {}
189
+
190
+ # initialise the set of 'always local' nodes which exist in all
191
+ # documents across a set and links are never rewritten to a node
192
+ # in another document
193
+ self._common_nodes = set()
194
+
195
+
196
+ def __repr__(self):
197
+ """Printable version of the object useful for debugging.
198
+ """
199
+
200
+ return "GuideNodeDocs(" + repr(sorted(self._nodes)) + ')'
201
+
202
+
203
+ def __contains__(self, name):
204
+ """Reports if a particular node name is present in the mapping
205
+ dictionary.
206
+ """
207
+
208
+ return name in self._nodes
209
+
210
+
211
+ def addnodes(self, doc):
212
+ """Merge the names of all the nodes in a GuideDoc document (and
213
+ the name of that document) to the mapping dictionary.
214
+ """
215
+
216
+ # get the name of the document
217
+ doc_name = doc.getname()
218
+
219
+ # go through the nodes in this new document
220
+ for node_name in doc.getnodenames():
221
+ # check if we already have a node of that name
222
+ if node_name in self._nodes:
223
+ # we do - if it's not a common node, we add a warning
224
+ # that we have a duplicate node
225
+ if node_name not in self._common_nodes:
226
+ print(self._common_nodes)
227
+ doc.addwarning(
228
+ f"node: @{node_name} same name already exists"
229
+ f" in document: {self._nodes[node_name]} -"
230
+ f" latter takes precedence for links")
231
+
232
+ else:
233
+ # we don't have this node yet - record it against this
234
+ # document
235
+ self._nodes[node_name] = doc_name
236
+
237
+
238
+ def addcommonnode(self, node_name):
239
+ """Add the named common node to the set of nodes which can exist
240
+ in multiple documents across a set without generating a warning.
241
+ Typically this is the index nodes.
242
+ """
243
+
244
+ self._common_nodes.add(node_name)
245
+
246
+
247
+ def fixlink(self, doc, target_name):
248
+ """This function is supplied the name of a target node for a
249
+ link and the document in which that link occurs. It returns a
250
+ 'fixed' link, which is one qualified with the name of another
251
+ document, if the link targets a node not in the current
252
+ document.
253
+
254
+ The following steps are checked in order of priority:
255
+
256
+ 1. If the link contains a document separator, it's assumed to
257
+ already be correct.
258
+
259
+ 2. If the target is in this document, leave it unqualified.
260
+
261
+ 3. If the target does not exist, return None (= not found / broken).
262
+
263
+ 4. Return the target prefixed with the document name and the
264
+ separator character.
265
+ """
266
+
267
+ # if the link is already qualified with a document name, assume
268
+ # it's correct and leave it alone
269
+ if DOC_SEPARATOR in target_name:
270
+ return target_name
271
+
272
+ # if the target is in the supplied document, we assume it's
273
+ # local and return it as is
274
+ if doc.getnode(target_name):
275
+ return target_name
276
+
277
+ # the link isn't in this document ...
278
+
279
+ # if the target node was not found across the set, return None
280
+ # to indicate it's a broken link
281
+ if target_name not in self._nodes:
282
+ return None
283
+
284
+ # the target is in another document - return it qualified
285
+ return self._nodes[target_name] + DOC_SEPARATOR + target_name
286
+
287
+
288
+
289
+ class GuideIndex(object):
290
+ """Represents the index node of a document. The class provides
291
+ methods to parse indexes in a specific source format and then render
292
+ them out again.
293
+
294
+ In addition, indices across multiple documents can be merged to
295
+ provide a common index across the set.
296
+
297
+ For the purposes of this class, indexes have a simple, consistent
298
+ structure. Each entry is structured as follows:
299
+
300
+ - each entry is called a 'term' and has a name, which is displayed
301
+ in the index
302
+
303
+ - each term may optionally have a link to a node giving the primary
304
+ definition
305
+
306
+ - each term may optionally have one or more secondary 'references',
307
+ which each have display text and a link to a node (which is
308
+ non-optional)
309
+ """
310
+
311
+
312
+ def __init__(self, *, termkey=indextermkey_factory([])):
313
+ """Initialise a GuideIndex object.
314
+
315
+ Keyword arguments:
316
+
317
+ termkey -- a function which takes a term in the index and
318
+ returns the sorting key; the first character of this sort key is
319
+ also used to group terms in the index.
320
+ """
321
+
322
+ super().__init__()
323
+
324
+ # initialise the dictionary of terms to be empty
325
+ self._terms = {}
326
+
327
+ # initialise the list of warnings to be empty
328
+ self._warnings = []
329
+
330
+ # initialise the header and footer (text before and after the
331
+ # index terms)
332
+ self.header = []
333
+ self.footer = []
334
+
335
+ # store the function to determine the key for a given term
336
+ self.termkey = termkey
337
+
338
+
339
+ def __repr__(self):
340
+ """Printable version of the object useful for debugging.
341
+ """
342
+
343
+ return "GuideIndex(" + repr(sorted(self._terms)) + ')'
344
+
345
+
346
+ def __contains__(self, term_text):
347
+ """Returns if the specified term text is present in the index.
348
+ """
349
+
350
+ return term_text in self._terms
351
+
352
+
353
+ def __getitem__(self, term_text):
354
+ """Get a dictionary entry giving details for the specified term.
355
+
356
+ The returned value should be considered opaque and this method
357
+ is really only intended for internal use. However, the return
358
+ value is a dictionary consisting of the following keys:
359
+
360
+ target -- a string giving the link target for the primary
361
+ definition (or None, if there is none)
362
+
363
+ refs -- a dictionary giving the secondary references for the
364
+ term; the dictionary keys are the reference text and the values
365
+ against those keys the reference target node
366
+ """
367
+
368
+ return self._terms[term_text]
369
+
370
+
371
+ def __iter__(self):
372
+ """Return an iterator for walking through the terms in the
373
+ index.
374
+ """
375
+
376
+ return iter(self._terms)
377
+
378
+
379
+ def getwarnings(self):
380
+ """Return the warnings from the index.
381
+ """
382
+
383
+ return self._warnings
384
+
385
+
386
+ def _addterm(self, add_term_text, add_term_dict):
387
+ self_term = self._terms.setdefault(add_term_text, {})
388
+
389
+ # if this entry specifies a primary target for the term, set it
390
+ if add_term_dict.get("target"):
391
+ if "target" in self_term:
392
+ if add_term_dict["target"] != self_term["target"]:
393
+ # there is already a primary target for this term
394
+ # and it's different - add a warning but don't
395
+ # change it
396
+ self._warnings.append(
397
+ f"term: '{add_term_text}' with target:"
398
+ f" {add_term_dict['target']} already exists"
399
+ " with different target:"
400
+ f" {self_term['target']}")
401
+
402
+ # ... or, if the target is not yet set, set it to this entry
403
+ else:
404
+ self_term["target"] = add_term_dict["target"]
405
+
406
+ # go through the references and add them to the term entry
407
+ self_refs = self_term.setdefault("refs", {})
408
+ for add_ref in add_term_dict["refs"]:
409
+ add_ref_target = add_term_dict["refs"][add_ref]
410
+ if add_ref in self_refs:
411
+ if add_ref_target != self_refs[add_ref]:
412
+ # a reference with the same text was found but the
413
+ # target was different - add a warning but don't
414
+ # change it
415
+ self._warnings.append(
416
+ f"term: '{add_term_text}' has reference:"
417
+ f" '{add_ref}' with target: {add_ref_target}"
418
+ " already exists with different target:"
419
+ f" {self_refs[add_ref]}")
420
+ else:
421
+ self_refs[add_ref] = add_ref_target
422
+
423
+
424
+ def parselines(self, lines):
425
+ """Parse lines (typically from a node) as an index. It will
426
+ populate all terms and their references in the index, as well
427
+ the index header and footer lines.
428
+
429
+ This method should only be called once per index.
430
+ """
431
+
432
+ # initialise the previous term found to 'not found yet'
433
+ prev_term = None
434
+
435
+ for line in lines:
436
+ # parse this line (adding the term and reference(s), if
437
+ # found) and get the term used in it (or the previous one,
438
+ # if one was not found, as this is continuing that)
439
+ term = self._parseline(line, prev_term)
440
+
441
+ # if a term was found, and we'd already started a footer,
442
+ # that footer turned out to be some non-index entry lines in
443
+ # the middle of an index that we can't handle (we can only
444
+ # handle a header and footer), so discard those and report a
445
+ # warning)
446
+ if term:
447
+ if self.footer:
448
+ self._warnings.append(
449
+ "ignoring intermediate block of lines in index"
450
+ f" - count: {len(self.footer)} starting with:"
451
+ f" {self.footer[0]}")
452
+ self.footer = []
453
+
454
+ # we didn't find a term, so this should be a header or a
455
+ # footer ...
456
+ else:
457
+ # there are no terms yet, so it's part of the header
458
+ if not self._terms:
459
+ self.header.append(line)
460
+
461
+ # we've got some terms, so this must be a footer (or
462
+ # intermediate text that we're going to discard when we
463
+ # find another term later, above)
464
+ #
465
+ # add the line to the footer unless it's blank and we
466
+ # haven't got any footer lines (which means it's a
467
+ # leading blank line we can ignore)
468
+ elif line or self.footer:
469
+ self.footer.append(line)
470
+
471
+ # store the term from this line (or continued from a
472
+ # previous line) as the new previous one
473
+ prev_term = term
474
+
475
+ # we've got to the end of the lines, so we just need to trim of
476
+ # any trailing blank lines in the header
477
+ #
478
+ # loop while there are still header lines and the last header
479
+ # line is blank
480
+
481
+ while self.header and (not self.header[-1]):
482
+ # remove the last header line
483
+ self.header = self.header[0:-1]
484
+
485
+
486
+ def _parseline(self, line, prev_term=None):
487
+ """Parse a line from a source index node and add the results to
488
+ the index held by this object. If a term was parsed, it is
489
+ returned for the caller to supply as prev_term in the next call.
490
+
491
+ Lines should be of the form:
492
+
493
+ - begin with 0-2 spaces
494
+
495
+ - have a term which is a block of static text or a link command;
496
+ if this is omitted, the line will continue the previous term
497
+ specified with prev_term
498
+
499
+ - optionally followed by 3 or more spaces and a list of
500
+ references, which must all be link commands
501
+
502
+ The text part of term matched is returned, if an entry was
503
+ parsed - this is returned; it can be supplied as the prev_term
504
+ parameter for the next line and will be used if the following
505
+ line doesn't have a term (allowing a term's references to be
506
+ spread over multiple lines). If a line is matched and continues
507
+ the prev_term, this term will be returned for this call.
508
+
509
+ If there are any problems adding an entry, such as duplicate
510
+ entries for the same term or reference with conflicting target
511
+ link information, warnings will be added.
512
+ """
513
+
514
+ # try to parse index entry from this line - this should always
515
+ # succeed but just return empty matching groups for some key
516
+ # things but, if it doesn't, we return None for 'no match'
517
+ m = INDEX_LINE_RE.match(line)
518
+ if not m:
519
+ self._warnings.append(
520
+ "cannot parse index entry from line: " + line)
521
+
522
+ return None
523
+
524
+ term_link_text, term_link_target, term_static, refs = (
525
+ m.group("link_text", "link_target", "static_text", "refs"))
526
+
527
+ # get the term for this entry in order or preference
528
+ term_text_markup = term_link_text or term_static or prev_term
529
+ if not term_text_markup:
530
+ # no valid term was found - ignore this line
531
+ return None
532
+
533
+ # render the text to remove formatting from the term dictionary
534
+ term_text = renderstring(term_text_markup.strip())
535
+
536
+ # loop whilst there are more references to parse, collecting
537
+ # them into refs_dict
538
+ refs_dict = {}
539
+ while refs:
540
+ # try to match the first reference entry
541
+ m = INDEX_REFS_RE.match(refs)
542
+
543
+ # no match - we're done with this line
544
+ if not m:
545
+ break
546
+
547
+ # get the parts of the reference entry
548
+ ref_text, ref_target, refs = (
549
+ m.group("link_text", "link_target", "remainder"))
550
+
551
+ # store it in the dict
552
+ refs_dict[ref_text.strip()] = ref_target
553
+
554
+ # if no link target in the term, nor any refs, this probably is
555
+ # not an index entry but some plain text - ignore this line and
556
+ # return that we're not in a term
557
+ if (not term_link_target) and (not refs_dict):
558
+ return None
559
+
560
+ # build a dictionary of details about the term (except the text)
561
+ # to use with _addterm()
562
+ term_dict = {}
563
+ if term_link_target:
564
+ term_dict["target"] = term_link_target
565
+ term_dict["refs"] = refs_dict
566
+
567
+ # add the term to the dictionary, flagging up any warnings about
568
+ # duplicates, etc.
569
+ self._addterm(term_text, term_dict)
570
+
571
+ # we added something to the index, so return the term we used,
572
+ # so it can be used for prev_term on the next line, if required
573
+ return term_text
574
+
575
+
576
+ def merge(self, merge_index):
577
+ """Merge another index into this one to create a common index
578
+ (e.g. across a set).
579
+
580
+ If there are any problems adding an entry, such as duplicate
581
+ entries for the same term or reference with conflicting target
582
+ link information, warnings will be added.
583
+ """
584
+
585
+ # go through the terms in the index we're merging and merge them
586
+ # into this one
587
+ for term in merge_index:
588
+ self._addterm(term, merge_index[term])
589
+
590
+
591
+ def format(self, line_maxlen, terms_width=DEFAULT_REFS_INDENT,
592
+ terms_gap=DEFAULT_REFS_GAP):
593
+ """Format the index for writing. The terms will be listed on
594
+ the left side, with the references on the right side, wrapped
595
+ to the maximum line width. The return value is a list of lines.
596
+
597
+ The width of the terms column will be terms_width, the
598
+ references starting after that. A minimum of terms_gap spaces
599
+ will be left between a term and a reference - if a term is
600
+ longer than this, the references will start on the following
601
+ line.
602
+
603
+ The terms are sorted according to the 'termkey' function
604
+ supplied to the constructor.
605
+ """
606
+
607
+ # store the previous term group (space for a symbol [see below],
608
+ # number or letter) - this is used to work out when to insert a
609
+ # blank line
610
+ prev_term_group = None
611
+
612
+ # counter for the number of links (used to track if the limit of
613
+ # 255 is exceeded)
614
+ num_links = 0
615
+
616
+ # initialise the returned lines list
617
+ index_lines = []
618
+
619
+ # work through the terms using the termkey function to sort them
620
+ # into order
621
+ for term_text in sorted(self, key=self.termkey):
622
+ # the grouping for this term is the first character of the
623
+ # sort key; if that was empty, we use a space
624
+ term_group = (self.termkey(term_text) or ' ')[0]
625
+
626
+ # if the group of this term is different from the previous
627
+ # one, we need to insert a blank line
628
+ if ((prev_term_group is not None)
629
+ and (term_group != prev_term_group)):
630
+
631
+ index_lines.append('')
632
+
633
+ # get the dictionary about this term
634
+ term_dict = self[term_text]
635
+
636
+ # add the term to the rendered and markup versions of the
637
+ # output
638
+ #
639
+ # the rendered version is used to calculate displayed widths
640
+ # for word wrap; the markup version is used for the actual
641
+ # output
642
+ line_render = ' ' + term_text + ' '
643
+ line_markup = (linkcmd(' ' + term_text + ' ', term_dict["target"])
644
+ if term_dict.get("target")
645
+ else (" @{b}" + term_text + "@{ub} "))
646
+
647
+ # increase the number of links, if the term has a target set
648
+ if term_dict.get("target"):
649
+ num_links += 1
650
+
651
+ # get the dictionary of references for this term
652
+ refs_dict = term_dict["refs"]
653
+
654
+ # if there are references, we need to space over to the
655
+ # references column from the term
656
+ if refs_dict:
657
+ # if the length of the rendered version, added to the
658
+ # minimum gap between it and the references, is over the
659
+ # width of the terms column, write out the term on a
660
+ # line of it's own and start a new indented line for the
661
+ # references
662
+ if len(line_render) + terms_gap > terms_width:
663
+ index_lines.append(line_markup)
664
+ line_markup = line_render = ' ' * terms_width
665
+
666
+
667
+ # the term and gap will fit in the terms column - add
668
+ # the number of spaces required to get into the
669
+ # references column
670
+ else:
671
+ tab = ' ' * (terms_width - len(line_render))
672
+ line_render += tab
673
+ line_markup += tab
674
+
675
+ # start with this being the first reference on a line
676
+ line_first = True
677
+
678
+ # work through the references, getting the reference name
679
+ # and flag if there are more references to come
680
+ for ref, more in _itermore(sorted(refs_dict)):
681
+ # references are space-padded at start and end
682
+ ref_text = ' ' + ref + ' '
683
+
684
+ # if the term is not the first on a line, it needs a
685
+ # space to separate it from the previous term
686
+ ref_pre = '' if line_first else ' '
687
+
688
+ # we need a comma after the reference if there are more
689
+ # to come
690
+ ref_post = ',' if more else ''
691
+
692
+ # if adding this reference to the line would cause it to
693
+ # be overlength, finish that line and start a new one
694
+ if (len(line_render + ref_pre + ref_text + ref_post)
695
+ > line_maxlen):
696
+
697
+ # write out this line
698
+ index_lines.append(line_markup)
699
+
700
+ # start new, indented line
701
+ line_markup = line_render = ' ' * terms_width
702
+
703
+ # we don't need the space before this term as this
704
+ # will be the first on the line
705
+ ref_pre = ''
706
+
707
+ # add this reference to the render and markup versions
708
+ # of the line
709
+ line_render += ref_pre + ref_text + ref_post
710
+ line_markup += (
711
+ ref_pre + linkcmd(ref_text, refs_dict[ref]) + ref_post)
712
+
713
+ # we're no longer the first term on the line (even if
714
+ # started a new one, we just added one that was the
715
+ # first)
716
+ line_first = False
717
+
718
+ num_links += 1
719
+
720
+ # add the last (uncompleted) line for this term the output
721
+ index_lines.append(line_markup)
722
+
723
+ # this term group as the previous, ready for the next one
724
+ prev_term_group = term_group
725
+
726
+ # generate a warning, if there are too many links in the index
727
+ # node
728
+ if num_links > 255:
729
+ self._warnings.append(
730
+ f"index node contains too many links: {num_links}")
731
+
732
+ # return the formatted index
733
+ return index_lines