tome / src / tome / AbstractWriter.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import Tome
import abc
import sys
import collections
import cStringIO

class TomeWriterException(Exception):
    def __init__(self, positioned, cause):
        Exception.__init__(self)

        if positioned is None:
            self.__pos = None
        elif isinstance(positioned, Tome.Position):
            self.__pos = positioned
        elif isinstance(positioned, Tome.Positioned):
            self.__pos = positioned.position()
        else:
            raise TypeError("Invalid position for TomeWriterException: expected a Tome.Position or Tome.Positioned object.")

        self.__cause = cause

    def __str__(self):
        if self.__pos is None:
            return "Error: %s" % (self.__cause)
        else:
            return "Error at %s: %s" % (self.__pos, self.__cause)

    def position(self):
        return self.__pos

    def cause(self):
        return self.__cause

LEVEL_LOWEST = -1
LEVEL_TOME = 0
LEVEL_PART = 1
LEVEL_BOOK = 2
LEVEL_CHAPTER = 3
LEVEL_SCENE = 4
LEVEL_PARAGRAPH = 5
LEVEL_NOTE = 6


class AbstractWriter(object):

    def __init__(self):
        self.tome = self.part = self.book = self.chapter = self.scene = self.par = None
        self.__numbers = (
            [0],            #part numbers
            [0,0],          #book numbers
            [0,0,0],        #chapter numbers
            [0,0,0,0],      #scene numbers
            [0,0,0,0,0],    #par numbers
            [0,0,0,0,0,0],  #note numbers
        )
        self.__notes = []

    class Note(object):
        def __init__(self, data):
            self.data = data

    def getNotes(self, level):
        notes = self.__notes
        for i in xrange(level):
            notes = notes[-1]

        def flatten(l):
            for el in l:
                if not isinstance(el, AbstractWriter.Note):
                    for sub in flatten(el):
                        yield sub
                else:
                    yield el.data

        return flatten(notes)
        

    def _stepNumbers(self, level):
        for i in xrange(len(self.__numbers[level-1])):
            self.__numbers[level-1][i] += 1

        #Reset the lower numbers
        for i in xrange(level, len(self.__numbers)):
            numbers = self.__numbers[i]
            for j in xrange(level, len(numbers)):
                numbers[j] = 0

        notes = self.__notes
        for i in xrange(1, level):
            notes = notes[-1]
        notes.append([])

    def listNumbers(self, level, relative=0):
        """
        Like `getNumber`, but returns a tuple of the numbers of all the levels up
        to (but not including) `relative`, relative to `relative`.
        """
        return tuple(self.getNumber(L, -1) for L in xrange(relative+1, level+1))

    def joinNumbers(self, glue, level, relative=0):
        return glue.join("%d" % number for number in self.listNumbers(level, relative))
        
    def getNumber(self, level, relative=-1):
        """
        Returns the current number of a section, relative to another level.

        For instance, you can find the number of the chapter within the current book, or within
        the current part, or within the entire tome. By default, returns the number relative to
        the next layer up (e.g., par in scene, scene in chapter, etc.).
        """
        return self.__numbers[level-1][relative]

    def write(self, tome):
        """
        The main API function which is called to generate the complete output for the specified
        |Tome| object based on this object's configuration.
        """

        self.tome = tome
        try:
            self._prepareOutput(tome)
            self._frontMatter(tome)

            for part in tome:
                self.part = part
                self._stepNumbers(LEVEL_PART)
                self._writePart(part)

            self._endMatter(tome)
            self._finishOutput(tome)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _prepareOutput(self, tome):
        """
        Called as the first step of `write`, this is typically used to open the output stream or
        create any output directories that are required.
        """
        pass

    def _frontMatter(self, tome):
        """
        Called as the second step of `write` (after `_prepareOutput`), this is typically used to generate
        any front matter for the document, such as title pages, tables of contents, etc.
        """
        pass

    def _endMatter(self, tome):
        """
        Called as the second-to-last step of `write` (immediately before `_finishOutput`), this is typically
        used to generate any back matter for the document, such as indices, appendicies, afterwards, etc.
        """
        pass

    def _finishOutput(self, tome):
        """
        Called as the final step of `write`, this is typically used to close the output stream or package up
        the generated files, as needed.
        """
        pass

    def _raiseError(self, position, e):
        trace = sys.exc_info()[2]
        raise TomeWriterException(position, e), None, trace

    def _writePart(self, part):
        try:
            self._preparePart(part)
            
            self._writePartTitle(part)
            for book in part:
                self.book = book
                self._stepNumbers(LEVEL_BOOK)
                self._writeBook(book)

            self._finishPart(part)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _preparePart(self, part):
        pass

    def _writePartTitle(self, part):
        pass

    def _finishPart(self, part):
        pass

    def _writeBook(self, book):
        try:
            self._prepareBook(book)
            
            self._writeBookTitle(book)
            for chapter in book:
                self.chapter = chapter
                self._stepNumbers(LEVEL_CHAPTER)
                self._writeChapter(chapter)

            self._finishBook(book)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _prepareBook(self, book):
        pass

    def _writeBookTitle(self, book):
        pass

    def _finishBook(self, book):
        pass

    def _writeChapter(self, chapter):
        try:
            self._prepareChapter(chapter)
            
            self._writeChapterTitle(chapter)
            sceneCount = len(chapter)
            lastScene = sceneCount-1
            for i in xrange(sceneCount):
                self.scene = chapter[i]
                self._stepNumbers(LEVEL_SCENE)
                self._writeScene(self.scene, i==0, i==lastScene)

            self._finishChapter(chapter)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _prepareChapter(self, chapter):
        pass

    def _writeChapterTitle(self, chapter):
        pass

    def _finishChapter(self, chapter):
        pass

    def _writeScene(self, scene, firstScene, lastScene):
        try:

            self._prepareScene(scene, firstScene)
            parCount = len(scene)
            lastPar = parCount-1
            for i in xrange(parCount):
                paragraph = scene[i]
                self.paragraph = paragraph
                self._stepNumbers(LEVEL_PARAGRAPH)

                tag = paragraph.tag()
                if tag not in ("p", "pre"):
                    raise Exception("Invalid toplevel element in scene: %s" % tag)

                if tag == "pre":
                    self._writePreformatted(paragraph, i==0, i==lastPar)
                else:
                    self._writeParagraph(paragraph, i==0, i==lastPar)
            self._finishScene(scene, lastScene)

        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _prepareScene(self, scene, firstScene):
        pass

    def _finishScene(self, scene, lastScene):
        pass

    def _writePreformatted(self, paragraph, firstPar, lastPar):
        try:
            self._preparePreformatted(paragraph, firstPar)
            for segment in paragraph:
                self._writePreformattedSegment(segment)
            self._finishPreformatted(paragraph, lastPar)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _preparePreformatted(self, paragraph, firstPar):
        pass

    def _finishPreformatted(self, paragraph, lastPar):
        pass

    def _writeParagraph(self, paragraph, firstPar, lastPar):
        try:
            self._prepareParagraph(paragraph, firstPar)
            for segment in paragraph:
                self._writeSegment(segment)
            self._finishParagraph(paragraph, lastPar)
        except TomeWriterException: raise
        except Exception, e: self._raiseError(None, e)

    def _prepareParagraph(self, paragraph, firstPar):
        pass

    def _finishParagraph(self, paragraph, lastPar):
        pass

    def _writePreformattedSegment(self, segment):
        return self._writeSegment(segment)

    def _writeSegment(self, segment):
        if isinstance(segment, Tome.TextSegment):
            try:
                self._writeText(segment.text(), segment)
            except TomeWriterException: raise
            except Exception, e: self._raiseError(segment, e)

        elif isinstance(segment, Tome.TaggedSegment):
            tag = segment.tag()

            try:
                #Formatting
                if tag in ("pre" , "b" , "i" , "em" , "u"):
                    self._writeFormatSegment(tag, segment)

                #Block segments
                elif tag in ("q", "sq", "bq", "p"):
                    self._writeBlockSegment(tag, segment)

                #Notes:
                elif tag == "n":
                    self._writeNote(segment)

                #Text objects
                elif tag in ("ellips", "md", "nd", "sp", "lnbrk"):
                    self._writeTextObject(tag, segment)

                #Accents
                elif tag in ("grave", "acute", "circumflex", "umlaut", "tilde", "cedilla"):
                    if len(segment) != 1 or not isinstance(segment[0], Tome.TextSegment):
                        raise Exception("Invalid use of %s accent: must have exactly one text segment child.")
                    target = segment[0].text()
                    if len(target) != 1:
                        raise Exception("Invalid use of %s accent: segment content must be a single character: " + target)
                    self._writeAccent(tag, target, segment)

                else:
                    raise Exception("Unhandled tag '%s'." % tag)
                    

            except TomeWriterException: raise
            except Exception, e: self._raiseError(segment, e)

        else:
            raise TypeError("Unexpected type for segment:" % repr(segment))

    def _writeNote(self, segment):
        """
        This is called when a note is encountered while writing output.
        The default implementation steps the note number (with `_stepNumbers`),
        and calls `_processNote` in order to get the data to associated with
        the note. This data is then added to the stored notes structure and can
        be retrieved with `getNotes`.
        """
        self._stepNumbers(LEVEL_NOTE)

        #Process and store the note's value.
        data = self._processNote(segment)
        note = AbstractWriter.Note(data)
        self.__notes[-1][-1][-1][-1][-1].append(note)

        return data

    def _processNote(self, segment):
        """
        This is called by `_writeNote` in order to process the content of the note and
        generate data to be associated with that note. A common thing to do is to replace
        your output stream with a string buffer and write the note segment to that with
        `_writeBlockSegment`. This ensures that embedded notes will be picked up as well.
        You can then return the string buffer as the data to be stored for this note, so
        that you can print it out later (for instance, at the end of the chapter).

        You will also likely want to get the note number with `getNumber`, *before* processing
        the note segment, because if there are embedded notes, that number will change.
        You can then store the number with the data as well.
        """
        return segment

    def _writeBlockSegment(self, tag, segment):
        self._prepareBlockSegment(tag, segment)

        notFirst = False
        parCount = len(segment)
        for parNum in xrange(parCount):
            par = segment[parNum]

            #There could be some empty text nodes that show up here, depending on how it's parsed.
            if isinstance(par, Tome.TextSegment) and len(par.text().strip()) == 0:
                continue
            if not isinstance(par, Tome.TaggedSegment) or par.tag() != "p":
                raise Exception("Block node may only contain \"p\" elements: found \"%s\"" % par.tag())

            #Don't actually put a par-break in front of the first paragraph in a block element (like a quoted string).
            if notFirst:
                cself._openPar(self, par)
                notFirst = True

            for child in par:
                self._writeSegment(child)
                dropCap = False

            if parNum != (parCount-1):
                self._closePar(par)

        self._finishBlockSegment(tag, segment)

    @abc.abstractmethod
    def _prepareBlockSegment(self, tag, segment):
        pass

    @abc.abstractmethod
    def _finishBlockSegment(self, tag, segment):
        pass

    @abc.abstractmethod
    def _openPar(self, par):
        """
        Called by `_writeBlockSegment` to open subsequent paragraphs within the block segment.
        This is NOT called for the first segment in the block, which is considered part of the current
        paragraph.
        """
        pass

    @abc.abstractmethod
    def _closePar(self, par):
        """
        Called by `_writeBlockSegment` to close all but the last paragraph within the block segment.
        """
        pass

    def _writeFormatSegment(self, tag, segment):
        """
        Writes the output for a formatting segment (e.g., bold, italics, etc.).
        This is called from `_writeSegment` for segments which are determined to be
        formatting segments.

        The default implementation uses `_prepareFormatSegment` and `_finishFormatSegment`
        to open and close the formatting. In between, it calls `_writeSegment` to write each of
        the children of the given segment.

        :param str tag: The tag for the segment, taken directly from `segment`.
        
        :param segment: The segment to write.
        :type segment: `Tome.TaggedSegment`.
        """
        self._prepareFormatSegment(tag, segment)
        for child in segment:
            self._writeSegment(child)
        self._finishFormatSegment(tag, segment)

    def _prepareFormatSegment(self, tag, segment):
        """
        Called from the default implementation of `_writeFormatSegment` in order to
        open the formatting. 
        """
        self._writeOut(self._formatPrefix(tag, segment))
        pass

    def _finishFormatSegment(self, tag, segment):
        """
        Called from the default implementation of `_writeFormatSegment` in order to
        close the formatting. 
        """
        self._writeOut(self._formatSuffix(tag, segment))

    @abc.abstractmethod
    def _formatPrefix(self, tag, segment):
        """
        Return a string which should prefix the content for the specified
        format segment (e.g., bold, italics, etc.). Used by default implementation
        of `_writeFormatSegment`.

        :param str tag: The tag for the segment, taken directly from `segment`.
        
        :param segment: The segment whose formatting tag is being requested.
        :type segment: `Tome.TaggedSegment`.
        """
        pass

    @abc.abstractmethod
    def _formatSuffix(self, tag, segment):
        """
        Return a string which should suffix the content for the specified
        format segment (e.g., bold, italics, etc.). Used by default implementation
        of `_writeFormatSegment`.

        :param str tag: The tag for the segment, taken directly from `segment`.
        
        :param segment: The segment whose formatting tag is being requested.
        :type segment: `Tome.TaggedSegment`.
        """
        pass

    @abc.abstractmethod
    def _writeOut(self, string):
        """
        Write the specified string to the output stream.

        :param str string: The string to write.
        """
        pass

    def _writeText(self, text, segment):
        """
        Write a text segment to the output stream. Default simply passes the text directly to `_writeOut`.


        :param str text: the text to write, taken directly from the `segment`.
        
        :param segment: The segment to write.
        :type segment: `Tome.TextSegment`
        """
        self._writeOut(text)

    @abc.abstractmethod
    def _writeTextObject(self, tag, segment):
        """
        Write a text object (mdash, ellips, etc.) to the output stream.

        :param str tag: The tag of the segment, describing what text object to generate. Taken directly from the `segment`.
        
        :param segment: The segment to write.
        :type segment: `Tome.TaggedSegment`
        """
        pass

    @abc.abstractmethod
    def _writeAccent(self, tag, char, segment):
        """
        Write an accented character to the output stream.

        :param str tag: The tag of the segment, describing what type of accent to apply. Taken directly from the `segment`.

        :param str char: The character to apply the accent to.
        
        :param segment: The segment to write.
        :type segment: `Tome.TaggedSegment`
        """
        pass
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.