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/set.py ADDED
@@ -0,0 +1,358 @@
1
+ # nextguidefmt/set.py
2
+
3
+ # Sets are groups of documents (files) which are processed together,
4
+ # with links between them and some other shared elements, such as index
5
+ # nodes.
6
+
7
+
8
+
9
+ import os
10
+
11
+ from .index import GuideNodeDocs, GuideIndex
12
+ from .node import LINE_MAXLEN
13
+ from .doc import GuideDoc, DOC_CMD_INDEX, DOC_MAXSIZE
14
+
15
+
16
+
17
+ # --- constants ---
18
+
19
+
20
+
21
+ # DEFAULT_INDEX_NAME = string
22
+ #
23
+ # The default name for an index node, if one is not defined.
24
+
25
+ DEFAULT_INDEX_NAME = "INDEX"
26
+
27
+
28
+
29
+ # CONSISTENT_DOC_CMDS = list
30
+ #
31
+ # The list of document level commands to check for consistency across a
32
+ # set.
33
+
34
+ CONSISTENT_DOC_CMDS = [ "author", "copyright", "version" ]
35
+
36
+
37
+
38
+ # --- functions ---
39
+
40
+
41
+
42
+ def _identity(i):
43
+ """Simple identity function which returns the single argument it is
44
+ passed. It is used as the default for the 'indextermkey' argument
45
+ in GuideSet.makeindices().
46
+ """
47
+
48
+ return i
49
+
50
+
51
+
52
+ # --- classes ---
53
+
54
+
55
+
56
+ class GuideSet(object):
57
+ """Handles a set of GuideDocs with interconnecting links and common
58
+ index.
59
+ """
60
+
61
+
62
+ def __init__(self, filenames, *, subindex_names=set()):
63
+ """Initialise the set of documents by reading in the supplied
64
+ list of filenames.
65
+
66
+ Keyword arguments:
67
+
68
+ subindex_names -- a list of node names which will also be
69
+ treated as index nodes and combined across the set; this is
70
+ useful if there are additional nodes acting as indices, separate
71
+ from the one named with the '@index' document command.
72
+ """
73
+
74
+ super().__init__()
75
+
76
+ # initialise a list of documents in the set as empty
77
+ self._docs = []
78
+
79
+ # initialise an empty dictionary of indices - this will be keyed
80
+ # on the node name of the index, as they are parsed, allowing
81
+ # multiple indices to be stored
82
+ self._indices = {}
83
+
84
+ # initialise a dictionary mapping nodes to documents
85
+ #
86
+ # this is used to provide an overall list of all nodes, and to
87
+ # qualify links with document names, when the link to nodes in
88
+ # other documents
89
+ #
90
+ # we add all the subindex names to the 'common nodes' list to
91
+ # avoid warnings if any appear in multiple documents; the index
92
+ # named with '@index' in each document will be added as the
93
+ # files are read later
94
+ self._node_docs = GuideNodeDocs()
95
+ for subindex_name in subindex_names:
96
+ self._node_docs.addcommonnode(subindex_name)
97
+
98
+ # also store the list of subindex node names from the supplied
99
+ # argument as we need it when we read the documents
100
+ self._subindex_names = subindex_names
101
+
102
+ # initialise the list of warnings at the set level to empty
103
+ self._warnings = []
104
+
105
+ # read in the document files in the set
106
+ self.readfiles(filenames)
107
+
108
+
109
+ def addwarning(self, warning):
110
+ """Add a warning to the list of warnings about this set.
111
+ """
112
+
113
+ self._warnings.append(warning)
114
+
115
+
116
+ def getwarnings(self):
117
+ """Return all the warnings from the set.
118
+
119
+ This will include set-level warnings, as well as warnings from
120
+ all the documents in it (which will include those from nodes
121
+ within them).
122
+ """
123
+
124
+ # start with an empty warnings list
125
+ warnings = []
126
+
127
+ # first, extend the list of warnings with those from each
128
+ # document
129
+ for doc in self._docs:
130
+ warnings.extend([ f"document: {doc.getname()} {warning}"
131
+ for warning in doc.getwarnings() ])
132
+
133
+ # add in our warnings - we do this after the document ones as
134
+ # these a generated after each document is processed
135
+ warnings.extend(self._warnings)
136
+
137
+ # add in the warnings from the set indices
138
+ for index in sorted(self._indices):
139
+ warnings.extend(
140
+ [ f"set index: {index} {warning}"
141
+ for warning in self._indices[index].getwarnings() ])
142
+
143
+ # return the composite list of warnings
144
+ return warnings
145
+
146
+
147
+ def readfiles(self, filenames):
148
+ """Read the list of document files into a set.
149
+ """
150
+
151
+ # go through the supplied list of filenames
152
+ for filename in filenames:
153
+ # read in that file and make a document
154
+ doc = GuideDoc(filename, subindex_names=self._subindex_names)
155
+
156
+ # add this document to the list of documents in the set
157
+ self._docs.append(doc)
158
+
159
+ # add the index node to the set of 'always local' nodes
160
+ index_node_name = doc.getcmd(DOC_CMD_INDEX)
161
+ if index_node_name:
162
+ self._node_docs.addcommonnode(index_node_name)
163
+
164
+ # add the nodes in this document to the GuideNodeDocs
165
+ # mapping object
166
+ self._node_docs.addnodes(doc)
167
+
168
+
169
+ def writetextfile(self, file):
170
+ """Write out the set to a single named file in a readable, plain
171
+ text, format without markup.
172
+ """
173
+
174
+ with open(file, 'w') as f:
175
+ for doc in self._docs:
176
+ print('\n'.join(doc.format(node_docs=self._node_docs,
177
+ markup=False,
178
+ skip_index=True)),
179
+ file=f)
180
+
181
+
182
+ def writefiles(self, dir):
183
+ """Write out the set to a series of files in the specified
184
+ directory.
185
+
186
+ The filenames will be the document names with '.gde' suffixed.
187
+ """
188
+
189
+ for doc in self._docs:
190
+ with (open(os.path.join(dir, doc.getname() + ".gde"), 'w')
191
+ as f):
192
+ print('\n'.join(doc.format(node_docs=self._node_docs)),
193
+ file=f)
194
+
195
+ # add a warning if this file is over the maximum size
196
+ # for a single NextGuide document
197
+ if f.tell() > DOC_MAXSIZE:
198
+ doc.addwarning(f"over maximum size: {DOC_MAXSIZE} bytes")
199
+
200
+
201
+ def checkconsistency(self):
202
+ """This method checks for consistency amongst several document
203
+ level commands across the set. If any are found to mismatch
204
+ with the first document in the set, a warning will be generated
205
+ for that document.
206
+
207
+ The document level commands checked are 'author', 'copyright'
208
+ and 'version'. The other document level commands are permitted
209
+ to differ without warning.
210
+ """
211
+
212
+ # the name of the first document in the set and its document
213
+ # command values
214
+ first_doc_name = None
215
+ first_doc_values = {}
216
+
217
+ for doc in self._docs:
218
+ # have we processed the first document yet?
219
+ if first_doc_name is None:
220
+ # no - store the name and store the document level
221
+ # command values we're checking
222
+ first_doc_name = doc.getname()
223
+ for cmd in CONSISTENT_DOC_CMDS:
224
+ first_doc_values[cmd] = doc.getcmd(cmd)
225
+
226
+ else:
227
+ # we're checking the second or a following document, so
228
+ # compare them with the first
229
+ for cmd in CONSISTENT_DOC_CMDS:
230
+ if first_doc_values[cmd] != doc.getcmd(cmd):
231
+ self.addwarning(
232
+ f"command: {cmd} in document:"
233
+ f" {doc.getname()} value:"
234
+ f" '{doc.getcmd(cmd)}' inconsistent with"
235
+ f" first document in set: {first_doc_name}"
236
+ f" value: '{first_doc_values[cmd]}'")
237
+
238
+
239
+ def print(self, *, markup=False):
240
+ """Print out the set of guide documents to standard output, with
241
+ a separator between each one.
242
+
243
+ The 'markup' option controls whether the output should be a
244
+ plain text 'readable' version (= False) or a guide ('.gde')
245
+ format version containing markup (= True).
246
+
247
+ If printing plain text any index nodes will be skipped. If
248
+ printing guide format files containing markup, a separator will
249
+ be printed between each file.
250
+ """
251
+
252
+ for doc in self._docs:
253
+ # we only print the filename of this document if rendering
254
+ # markup format output and there's more than one document in
255
+ # the set
256
+ if markup and len(self._docs) > 1:
257
+ print()
258
+ print(f"=== {doc.getname()} ===")
259
+ print()
260
+
261
+ # print the formatted lines
262
+ for line in doc.format(node_docs=self._node_docs,
263
+ markup=markup, skip_index=not markup):
264
+ print(line)
265
+
266
+
267
+ def getnodedocs(self):
268
+ """Return a dictionary keyed on the name of all nodes in the
269
+ set, with the values as a list of the documents in which that
270
+ node is defined.
271
+
272
+ This is primarily useful as a debugging or informational
273
+ function.
274
+ """
275
+
276
+ # create a dictionary of node names
277
+ node_names = {}
278
+
279
+ # go through the documents in the set, adding the names of all
280
+ # the nodes to their entry in the above dictionary, creating it,
281
+ # if required
282
+ for doc in self._docs:
283
+ for node_name in doc.getnodenames():
284
+ node_names.setdefault(node_name, []).append(doc.getname())
285
+
286
+ # return the dictionary
287
+ return node_names
288
+
289
+
290
+ def makeindices(self, *, line_maxlen=LINE_MAXLEN, indextermkey=_identity):
291
+ """Make a consolidated indices for the set, merging together the
292
+ index pages with the same node name as each other.
293
+
294
+ This means that all index nodes which have the same name will
295
+ be combined and have the same entries across the set.
296
+
297
+ Keyword arguments:
298
+
299
+ line_maxlen -- the maximum line length; lines longer than this
300
+ will be word-wrapped (unless matching the 'literal' format).
301
+
302
+ indextermkey -- a function which maps a term to its key to use
303
+ use when sorting and grouping them in the index.
304
+ """
305
+
306
+ # initialise an empty set of indices as a dictionary
307
+ #
308
+ # the dictionary will be keyed off each index node name across
309
+ # the set
310
+ self._indices = {}
311
+
312
+ # go through the documents in the set, building the consolidated
313
+ # indices
314
+ for doc in self._docs:
315
+ # parse the indices in this document (which will consist of
316
+ # the node named by the '@index' command, plus the
317
+ # additional subindex nodes)
318
+ doc.parseindices()
319
+
320
+ # work through the indices in the document
321
+ for index_name in doc.getindices():
322
+ # add this index name to the common nodes set for the
323
+ # consolidated index (so we don't create warnings about
324
+ # the node existing in multiple documents, etc.)
325
+ self._node_docs.addcommonnode(index_name)
326
+
327
+ # if we haven't already started an index with the same
328
+ # name as this one, create it
329
+ if index_name not in self._indices:
330
+ self._indices[index_name] = (
331
+ GuideIndex(termkey=indextermkey))
332
+
333
+ # merge this document's index into the consolidated one
334
+ # under the same name
335
+ self._indices[index_name].merge(doc.getindex(index_name))
336
+
337
+
338
+ # create a dictionary, keyed off the index node name, of
339
+ # formatted text indices from those built above
340
+ formatted_indices = {
341
+ index_name:
342
+ self._indices[index_name].format(line_maxlen)
343
+ for index_name in self._indices }
344
+
345
+
346
+ # go back through the documents in the set, replacing the indices
347
+ for doc in self._docs:
348
+ for index_name in doc.getindices():
349
+ # get the existing index (for the header and footer lines)
350
+ index = doc.getindex(index_name)
351
+
352
+ # replace the node with the same name, using the header
353
+ # and footer from the original node, and the new
354
+ # consolidated index between
355
+ doc.getnode(index_name).replacelines(
356
+ ((index.header + ['']) if index.header else [])
357
+ + formatted_indices[index_name]
358
+ + (([''] + index.footer) if index.footer else []))
nextguidefmt/token.py ADDED
@@ -0,0 +1,197 @@
1
+ # nextguidefmt/token.py
2
+
3
+ # Tokens are pieces of text in a NextGuide document and can be literal
4
+ # text or commands.
5
+ #
6
+ # This module help parse and render these.
7
+
8
+
9
+
10
+ import re
11
+
12
+
13
+
14
+ # --- constants ---
15
+
16
+
17
+
18
+ # <?>_RESTR = string
19
+ # <?>_RE = re.Pattern
20
+ #
21
+ # Regular expressions to match various bits of NextGuide markup.
22
+
23
+
24
+ # link to another node
25
+ LINK_RESTR = r'@{ *"(?P<link_text>[^"]+)" LINK (?P<link_target>[^ }]+) *}'
26
+ LINK_RE = re.compile(LINK_RESTR)
27
+
28
+ # justify attribute - these are a subset of formatting attributes so
29
+ # must be checked first
30
+ JUSTIFICATION_RESTR = r'@{(?P<justification>[rc])}'
31
+ JUSTIFICATION_RE = re.compile(JUSTIFICATION_RESTR)
32
+
33
+ # formatting attribute
34
+ ATTR_RESTR = r"@{\w+}"
35
+ ATTR_RE = re.compile(ATTR_RESTR)
36
+
37
+ # literal characters
38
+ LITERALTOKEN_RESTR = r"@(?P<char>[^{])"
39
+ LITERALTOKEN_RE = re.compile(LITERALTOKEN_RESTR)
40
+
41
+ # plain (unformatted) word (as opposed to markup)
42
+ WORD_RESTR = r"[^@ ]+"
43
+
44
+ # one or more spaces
45
+ SPACE_RESTR = r"(?P<space> +)"
46
+ SPACE_RE = re.compile(SPACE_RESTR)
47
+
48
+ # match any type of markup token or word or block of spaces
49
+ TOKEN_RE = re.compile(r"(?P<token>"
50
+ + LINK_RESTR
51
+ + r'|' + ATTR_RESTR
52
+ + r'|' + LITERALTOKEN_RESTR
53
+ + r'|' + WORD_RESTR
54
+ + r'|' + SPACE_RESTR
55
+ + r')'
56
+ + r"(?P<remainder>.*)")
57
+
58
+ # start of a new node
59
+ NODE_CMDS_RE = re.compile(r"@node (?P<name>\S+)")
60
+
61
+ # nodal commands for a linked node token
62
+ NODE_LINK_CMDS_RE = re.compile(
63
+ r"@(?P<link>(node|prev|next|toc)) (?P<name>\S+)")
64
+
65
+ # lines to ignore:
66
+ #
67
+ # - a token with hyphens (a separator between nodes), or
68
+ #
69
+ # - a remark command
70
+ IGNORE_RE = re.compile(r"@(-+|rem\s)")
71
+
72
+
73
+ # LITERALLINE_RE = string
74
+ #
75
+ # Regular expression to match lines which must be included in the output
76
+ # guide literally (i.e. without reformatting).
77
+
78
+ LITERALLINE_RE = re.compile(
79
+ r'('
80
+
81
+ # lines with leading spaces
82
+ + r"\s+"
83
+
84
+ # lines with 3 or more consecutive spaces
85
+ + r"|.+\s{3,}"
86
+
87
+ # lines with headers
88
+ + r"|.*@{h\d}"
89
+
90
+ # lines with centred or right-justified text
91
+ + r"|@{[cr]}"
92
+
93
+ # lines consisting solely of a single link
94
+ + r'|' + LINK_RESTR + r'$'
95
+
96
+ + r')')
97
+
98
+
99
+
100
+ # --- functions ---
101
+
102
+
103
+
104
+ def rendertoken(t, *, link_bracket=False):
105
+ """Return a single rendered NextGuide token (which could be a
106
+ literal piece of text, a command, or block of spaces) into the plain
107
+ text equivalent (without formatting) that would be displayed on
108
+ screen.
109
+
110
+ This is used to work out the length of rendered markup and calculate
111
+ displayed line lengths; it is not used when writing out guide files,
112
+ unless a readable, plain text version is requested.
113
+
114
+ 'link_bracket' will cause links with spaces at the beginning and end
115
+ of the link text to have those replaced by angle brackets ('<' and
116
+ '>'). This doesn't change their length but does highlight that they
117
+ would have been links (and makes the multiple spaces look less odd).
118
+ """
119
+
120
+ # if the token is a link, use the displayed text field
121
+ m = LINK_RE.match(t)
122
+ if m:
123
+ t = m["link_text"]
124
+ if link_bracket and t.startswith(' ') and t.endswith(' '):
125
+ return '<' + t[1:-1] + '>'
126
+ return m["link_text"]
127
+
128
+ # if the token is a literal character, convert that to the displayed
129
+ # character
130
+ m = LITERALTOKEN_RE.match(t)
131
+ if m:
132
+ c = m["char"]
133
+
134
+ # '@(' is the copyright sign
135
+ if c == '(':
136
+ return "\N{COPYRIGHT SIGN}"
137
+
138
+ # everything else we treat as whatever is after the '@'
139
+ else:
140
+ return c
141
+
142
+ # attribute formatting codes don't render to anything displayed
143
+ m = ATTR_RE.match(t)
144
+ if m:
145
+ return ''
146
+
147
+ # we have a literal word or block of spaces - just use that directly
148
+ return t
149
+
150
+
151
+
152
+ def renderstring(s, *, link_bracket=False, line_maxlen=None):
153
+ """Return a string containing tokens (literals, commands, spaces,
154
+ etc.) rendered into their plain text equivalent. It is a wrapper
155
+ around rendertoken() which iteratively renders all the tokens in a
156
+ string.
157
+
158
+ The 'link_bracket' argument is passed on to rendertoken().
159
+ """
160
+
161
+ # start with the rendered string empty
162
+ r = ''
163
+
164
+ # default to no (= left) justification, unless specified
165
+ justification = None
166
+
167
+ # go through the string matching tokens (markup, literal or spaces)
168
+ remainder = s
169
+ while remainder:
170
+ m = TOKEN_RE.match(remainder)
171
+
172
+ # if we couldn't match a token, something has gone irretrievably
173
+ # wrong (probably with the regexp)
174
+ if not m:
175
+ raise ValueError("failed to match next token in: " + remainder)
176
+
177
+ token, remainder = m.group("token", "remainder")
178
+
179
+ # if a justification token is found, set that and loop to the next,
180
+ # else render the token or literal
181
+ j = JUSTIFICATION_RE.match(token)
182
+ if j:
183
+ justification = j.group("justification")
184
+ else:
185
+ r += rendertoken(token, link_bracket=link_bracket)
186
+
187
+ # if a justification token was encountered, justify the line accordingly
188
+ if justification and line_maxlen:
189
+ if justification == 'c':
190
+ r = ' ' * ((line_maxlen - len(r)) // 2) + r
191
+ elif justification == 'r':
192
+ r = ' ' * (line_maxlen - len(r)) + r
193
+ else:
194
+ raise AssertionError(
195
+ "invalid justification mode: " + justification)
196
+
197
+ return r