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
|
# Package : omniEvents
# docbook2text.py Created : 2004/08/13
# Author : Alex Tingle
#
# Copyright (C) 2004,2005 Alex Tingle.
#
# This file is part of the omniEvents application.
#
# omniEvents is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# omniEvents is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import sys
import string
import getopt
import xml.sax
import xml.sax.handler
def _db(message):
pass
class Element:
def __init__(self,handler,name,attrs):
self.handler=handler
self.name=name
self.attrs=attrs
self.margin_left=0
if handler.stack:
self.parent=handler.stack[-1]
else:
self.parent=None
def characters(self,content):
"""Pass content to parent content, by default."""
if self.parent:
self.parent.characters(content)
def end(self):
pass
def ancestor(self,names):
e=self.parent
while e:
if e.name in names:
return e
e=e.parent
return None
class Section(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.depth=0
e=self.ancestor([name])
if e:
self.depth=e.depth+1
if self.depth<len(handler.section):
handler.section[self.depth]+=1
else:
handler.section.append(1)
def end(self):
for d in range(self.depth+1,len(handler.section)):
handler.section[d]=0
class VariableList(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
handler.margin_left+=4
def end(self):
self.handler.margin_left-=4
class LiteralLayout(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.marginStr=' '*handler.margin_left
self.handler.outfile.write(self.marginStr)
def characters(self,content):
content=string.replace(content,'\n','\n'+self.marginStr)
self.handler.outfile.write(content)
def end(self):
self.handler.outfile.write('\n\n')
self.handler.cursor=0
class Para(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.space=1
def tomargin(self):
h=self.handler
if h.cursor>h.margin_left:
h.outfile.write('\n'+' '*h.margin_left)
else:
h.outfile.write(' '*(h.margin_left-handler.cursor))
h.cursor=h.margin_left
self.space=1
def addspace(self):
"""Add a space."""
if not self.space:
h=self.handler
if h.cursor<h.margin_left or h.cursor>=h.columns:
self.tomargin()
else:
h.outfile.write(' ')
h.cursor+=1
self.space=1
def addword(self,word):
h=self.handler
if h.cursor<h.margin_left or \
len(word)+h.cursor>h.columns:
self.tomargin()
h.outfile.write(word)
h.cursor+=len(word)
self.space=0
def characters(self,content):
h=self.handler
if content[0] in string.whitespace:
self.addspace()
first=1
for word in string.split(content):
if not first:
self.addspace()
first=0
self.addword(word)
if content[-1] in string.whitespace:
self.addspace()
def end(self):
self.handler.outfile.write('\n\n')
self.handler.cursor=0
class Title(Para):
def __init__(self,handler,name,attrs):
Para.__init__(self,handler,name,attrs)
self.width=0;
self.titleof=self.ancestor(['section','example','refsect1'])
if self.titleof and self.titleof.name=='section':
if self.titleof.depth>0:
x=[]
for i in range(0,self.titleof.depth+1):
x.append(str(handler.section[i]))
Para.characters(self,string.join(x,'.')+' ')
else:
Para.characters(self,str(handler.section[0])+'. ')
elif self.titleof and self.titleof.name=='example':
Para.characters(self,'Example: ')
elif self.titleof and self.titleof.name=='refsect1':
handler.margin_left-=3
def characters(self,content):
if self.titleof and self.titleof.name=='refsect1':
content=string.upper(content)
Para.characters(self,content)
self.width=max(self.width,self.handler.cursor)
def end(self):
t=self.titleof
if t and t.name=='section' and t.depth==0:
self.tomargin()
Para.characters(self,'='*self.width)
elif t and t.name=='example':
pass
elif t and t.name=='refsect1':
handler.margin_left+=3
else:
self.tomargin()
Para.characters(self,'-'*self.width)
Para.end(self)
class Span(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.content=''
def characters(self,content):
self.content+=content
def end(self):
self.parent.characters(self.content)
class Quote(Span):
def __init__(self,handler,name,attrs):
Span.__init__(self,handler,name,attrs)
def end(self):
self.parent.characters('"'+self.content+'"')
class Command(Span):
def __init__(self,handler,name,attrs):
Span.__init__(self,handler,name,attrs)
def end(self):
self.parent.characters('`'+self.content+"'")
class Replaceable(Span):
def __init__(self,handler,name,attrs):
Span.__init__(self,handler,name,attrs)
def end(self):
self.parent.characters('<'+self.content+'>')
class OrderedList(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.index=0
class ListItem(Para):
def __init__(self,handler,name,attrs):
Para.__init__(self,handler,name,attrs)
self.tomargin()
self.indent=3
if self.parent and self.parent.name=='itemizedlist':
handler.outfile.write(' o ')
elif self.parent and self.parent.name=='orderedlist':
self.parent.index+=1
index=' %s) '%str(self.parent.index)
handler.outfile.write(index)
self.indent=len(index)
else:
handler.outfile.write(' ')
handler.margin_left+=self.indent
handler.cursor=handler.margin_left
def end(self):
handler.margin_left-=self.indent
class Term(Para):
def __init__(self,handler,name,attrs):
Para.__init__(self,handler,name,attrs)
handler.margin_left-=3
self.tomargin()
#handler.outfile.write(' * ')
#handler.margin_left+=3
#handler.cursor=handler.margin_left
def end(self):
self.characters(':')
self.handler.margin_left+=3
class InformalTable(Para):
def __init__(self,handler,name,attrs):
Para.__init__(self,handler,name,attrs)
self.content=[]
self.columns=0
def characters(self,content):
pass
def end(self):
colwidth=[0]*self.columns
for row in self.content:
for i in range(0,len(row)):
colwidth[i]=max(colwidth[i],len(row[i]))
# Emit table.
for row in self.content:
self.tomargin()
for i in range(0,len(row)):
self.handler.outfile.write(' '+string.ljust(row[i],colwidth[i]))
self.handler.outfile.write('\n')
self.handler.cursor=0
self.handler.outfile.write('\n')
self.handler.cursor=0
class Row(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.informaltable=self.ancestor(['informaltable'])
self.informaltable.content.append([])
def end(self):
if self.parent.name=='thead':
divider=[]
for e in self.informaltable.content[-1]:
divider.append('-'*len(e))
self.informaltable.content.append(divider)
class Entry(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
self.informaltable=self.ancestor(['informaltable'])
it=self.informaltable
it.content[-1].append('')
it.columns=max(it.columns,len(it.content[-1]))
def characters(self,content):
cleancontent=string.join(string.split(content))
if not cleancontent:
return
row=self.informaltable.content[-1]
if cleancontent[0] not in ' )]' and \
row[-1] and row[-1][-1] not in ' ([':
row[-1]+=' '
row[-1]+=cleancontent
class RefNameDiv(Para):
def __init__(self,handler,name,attrs):
Para.__init__(self,handler,name,attrs)
Para.characters(self,'-'*handler.columns)
class RefName(Span):
def __init__(self,handler,name,attrs):
Span.__init__(self,handler,name,attrs)
def end(self):
self.parent.characters(self.content+' - ')
class RefSect1(Element):
def __init__(self,handler,name,attrs):
Element.__init__(self,handler,name,attrs)
handler.margin_left+=3
def end(self):
handler.margin_left-=3
elementMap={
'title' :Title,
'section' :Section,
'literallayout' :LiteralLayout,
'programlisting':LiteralLayout,
'para' :Para,
'quote' :Quote,
'command' :Command,
'literal' :Command,
'orderedlist' :OrderedList,
'listitem' :ListItem,
'term' :Term,
'informaltable' :InformalTable,
'row' :Row,
'entry' :Entry,
'refnamediv' :RefNameDiv,
'refname' :RefName,
'refsect1' :RefSect1,
'cmdsynopsis' :Para,
'replaceable' :Replaceable,
'variablelist' :VariableList
}
class Docbook2TextHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.outfile=sys.stdout
self.columns=80
self.stack=[]
self.margin_left=0
self.cursor=0
self.section=[0]
def set_columns(self,c):
self.columns=c
def set_outfile(self,filename):
self.outfile=open(filename)
def startDocument(self):
_db('startDocument')
def endDocument(self):
_db('endDocument')
def startElement(self,name,attrs):
_db('-'*len(self.stack)+name)
element=None
if elementMap.has_key(name):
element=elementMap[name](self,name,attrs)
else:
element=Element(self,name,attrs)
self.stack.append(element)
self.margin_left+=self.stack[-1].margin_left
def endElement(self,name):
assert(self.stack)
assert(name==self.stack[-1].name)
self.stack[-1].end()
self.margin_left-=self.stack[-1].margin_left
del self.stack[-1]
def characters(self,content):
if isinstance(content,unicode):
content=content.encode("iso-8859-1", "replace")
self.stack[-1].characters(content)
#end class Docbook2TextHandler
def usage():
sys.stderr.write("""
Convert a DocBook XML file into text.
syntax: python docbook2text.py OPTIONS FILES
OPTIONS: DEFAULT:
-c COLUMNS Width of the output. 80
-o FILE Filename for the output. standard output
-v Be verbose.
-h Show this text.
""")
################################################################################
# If this file is executed directly, then we start here.
if(__name__=="__main__"):
handler=Docbook2TextHandler()
try:
opts,args=getopt.getopt(sys.argv[1:],"c:o:vh")
except getopt.error:
# print help information and exit:
usage()
sys.exit(-1)
for option, optarg in opts:
if option=='-c':
handler.set_columns(optarg)
elif option=='-o':
handler.set_outfile(optarg)
elif option=='-v':
_db=lambda message: sys.stderr.write(message+'\n')
elif option=='-h':
usage()
sys.exit(0)
else:
usage()
sys.exit(-1)
if args:
for f in args:
xml.sax.parse(f,handler)
else:
xml.sax.parse(sys.stdin,handler)
|