Debian Codegraph @

src/odf/teletype.py

raw
1 #
2 # Create and extract text from ODF, handling whitespace correctly.
3 # Copyright (C) 2008 J. David Eisenberg
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19
20 """
21 Class for handling whitespace properly in OpenDocument.
22
23 While it is possible to use getTextContent() and setTextContent()
24 to extract or create ODF content, these won't extract or create
25 the appropriate <text:s>, <text:tab>, or <text:line-break>
26 elements. This module takes care of that problem.
27 """
28
29 from .element import Node
30 from .text import LineBreak, S, Tab
31
32
33 class WhitespaceText:
34 def __init__(self):
35 self.textBuffer = []
36 self.spaceCount = 0
37
38 def addTextToElement(self, odfElement, s):
39 """Process an input string, inserting
40 <text:tab> elements for '\t',
41 <text:line-break> elements for '\n', and
42 <text:s> elements for runs of more than one blank.
43 These will be added to the given element.
44 """
45 i = 0
46 ch = ' '
47
48 # When we encounter a tab or newline, we can immediately
49 # dump any accumulated text and then emit the appropriate
50 # ODF element.
51 #
52 # When we encounter a space, we add it to the text buffer,
53 # and then collect more spaces. If there are more spaces
54 # after the first one, we dump the text buffer and then
55 # then emit the appropriate <text:s> element.
56
57 while i < len(s):
58 ch = s[i]
59 if ch == '\t':
60 self._emitTextBuffer(odfElement)
61 odfElement.addElement(Tab())
62 i += 1
63 elif ch == '\n':
64 self._emitTextBuffer(odfElement)
65 odfElement.addElement(LineBreak())
66 i += 1
67 elif ch == ' ':
68 self.textBuffer.append(' ')
69 i += 1
70 self.spaceCount = 0
71 while i < len(s) and (s[i] == ' '):
72 self.spaceCount += 1
73 i += 1
74 if self.spaceCount > 0:
75 self._emitTextBuffer(odfElement)
76 self._emitSpaces(odfElement)
77 else:
78 self.textBuffer.append(ch)
79 i += 1
80
81 self._emitTextBuffer(odfElement)
82
83 def _emitTextBuffer(self, odfElement):
84 """Creates a Text Node whose contents are the current textBuffer.
85 Side effect: clears the text buffer.
86 """
87 if len(self.textBuffer) > 0:
88 odfElement.addText(''.join(self.textBuffer))
89 self.textBuffer = []
90
91 def _emitSpaces(self, odfElement):
92 """Creates a <text:s> element for the current spaceCount.
93 Side effect: sets spaceCount back to zero
94 """
95 if self.spaceCount > 0:
96 spaceElement = S(c=self.spaceCount)
97 odfElement.addElement(spaceElement)
98 self.spaceCount = 0
99
100
101 def addTextToElement(odfElement, s):
102 wst = WhitespaceText()
103 wst.addTextToElement(odfElement, s)
104
105
106 def extractText(odfElement):
107 '''Extract text content from an Element, with whitespace represented
108 properly. Returns the text, with tabs, spaces, and newlines
109 correctly evaluated. This method recursively descends through the
110 children of the given element, accumulating text and "unwrapping"
111 <text:s>, <text:tab>, and <text:line-break> elements along the way.
112 '''
113 result = []
114
115 if len(odfElement.childNodes) != 0:
116 for child in odfElement.childNodes:
117 if child.nodeType == Node.TEXT_NODE:
118 result.append(child.data)
119 elif child.nodeType == Node.ELEMENT_NODE:
120 subElement = child
121 tagName = subElement.qname
122 if tagName == ('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'line-break'):
123 result.append('\n')
124 elif tagName == ('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'tab'):
125 result.append('\t')
126 elif tagName == ('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 's'):
127 c = subElement.getAttribute('c')
128 if c:
129 spaceCount = int(c)
130 else:
131 spaceCount = 1
132
133 result.append(' ' * spaceCount)
134 else:
135 result.append(extractText(subElement))
136 return ''.join(result)