[Zope3-checkins] CVS: zopeproducts/zwiki/renderer/StructuredText - ClassicDocumentClass.py:1.1 ClassicStructuredText.py:1.1 DocBookClass.py:1.1 DocumentClass.py:1.1 DocumentWithImages.py:1.1 HTMLClass.py:1.1 HTMLWithImages.py:1.1 ST.py:1.1 STDOM.py:1.1 STNG.txt:1.1 STletters.py:1.1 StructuredText.py:1.1 __init__.py:1.1 ts_regex.py:1.1
Stephan Richter
srichter@cbu.edu
Tue, 8 Apr 2003 22:49:13 -0400
Update of /cvs-repository/zopeproducts/zwiki/renderer/StructuredText
In directory cvs.zope.org:/tmp/cvs-serv9806/renderer/StructuredText
Added Files:
ClassicDocumentClass.py ClassicStructuredText.py
DocBookClass.py DocumentClass.py DocumentWithImages.py
HTMLClass.py HTMLWithImages.py ST.py STDOM.py STNG.txt
STletters.py StructuredText.py __init__.py ts_regex.py
Log Message:
- Moved renderers to own sub-module.
- Implemented comments via renderers
- Updated to latest version of StructuredText (now Zope 2 HEAD version)
=== Added File zopeproducts/zwiki/renderer/StructuredText/ClassicDocumentClass.py === (517/617 lines abridged)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import re, ST, STDOM
from STletters import letters
from types import StringType, UnicodeType, ListType
StringTypes = (StringType, UnicodeType)
class StructuredTextExample(ST.StructuredTextParagraph):
"""Represents a section of document with literal text, as for examples"""
def __init__(self, subs, **kw):
t=[]; a=t.append
for s in subs: a(s.getNodeValue())
ST.StructuredTextParagraph.__init__(self, '\n\n'.join(t), (), **kw)
def getColorizableTexts(self): return ()
def setColorizableTexts(self, src): pass # never color examples
class StructuredTextBullet(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextNumbered(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextDescriptionTitle(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextDescriptionBody(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextDescription(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
def __init__(self, title, src, subs, **kw):
ST.StructuredTextParagraph.__init__(self, src, subs, **kw)
self._title=title
def getColorizableTexts(self): return self._title, self._src
[-=- -=- -=- 517 lines omitted -=- -=- -=-]
s,
expr = re.compile('\s*\*\*([ \n%s0-9.:/;\-,!\?\'\"]+)\*\*' % letters).search
):
r=expr(s)
if r:
start, end = r.span(1)
return (StructuredTextStrong(s[start:end]), start-2, end+2)
else:
return None
def doc_href1(self, s,
expr=re.compile("(\"[ %s0-9\n\-\.\,\;\(\)\/\:\/\*\']+\")(:)([a-zA-Z0-9\@\.\,\?\!\/\:\;\-\#\~]+)([,]*\s*)" % letters).search
):
return self.doc_href(s, expr)
def doc_href2(self, s,
expr=re.compile('(\"[ %s0-9\n\-\.\:\;\(\)\/\*\']+\")([,]+\s+)([a-zA-Z0-9\@\.\,\?\!\/\:\;\-\#\~]+)(\s*)' % letters).search
):
return self.doc_href(s, expr)
def doc_href(self, s, expr, punctuation = re.compile("[\,\.\?\!\;]+").match):
r=expr(s)
if r:
# need to grab the href part and the
# beginning part
start,e = r.span(1)
name = s[start:e]
name = name.replace('"','',2)
#start = start + 1
st,end = r.span(3)
if punctuation(s[end-1:end]):
end = end -1
link = s[st:end]
#end = end - 1
# name is the href title, link is the target
# of the href
return (StructuredTextLink(name, href=link),
start, end)
#return (StructuredTextLink(s[start:end], href=s[start:end]),
# start, end)
else:
return None
=== Added File zopeproducts/zwiki/renderer/StructuredText/ClassicStructuredText.py === (449/549 lines abridged)
#! /usr/bin/env python -- # -*- python -*-
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
'''Structured Text Manipulation
Parse a structured text string into a form that can be used with
structured formats, like html.
Structured text is text that uses indentation and simple
symbology to indicate the structure of a document.
A structured string consists of a sequence of paragraphs separated by
one or more blank lines. Each paragraph has a level which is defined
as the minimum indentation of the paragraph. A paragraph is a
sub-paragraph of another paragraph if the other paragraph is the last
preceding paragraph that has a lower level.
Special symbology is used to indicate special constructs:
- A single-line paragraph whose immediately succeeding paragraphs are lower
level is treated as a header.
- A paragraph that begins with a '-', '*', or 'o' is treated as an
unordered list (bullet) element.
- A paragraph that begins with a sequence of digits followed by a
white-space character is treated as an ordered list element.
- A paragraph that begins with a sequence of sequences, where each
sequence is a sequence of digits or a sequence of letters followed
by a period, is treated as an ordered list element.
- A paragraph with a first line that contains some text, followed by
some white-space and '--' is treated as
a descriptive list element. The leading text is treated as the
element title.
- Sub-paragraphs of a paragraph that ends in the word 'example' or the
word 'examples', or '::' is treated as example code and is output as is.
[-=- -=- -=- 449 lines omitted -=- -=- -=-]
text)
text = re.sub(
r'([\0- ,])\[([^]]+)\.html\]([\0- ,.:])',
r'\1<a href="\2.html">[\2]</a>\3',
text)
return HTML(text,level=level)
def main():
import sys, getopt
opts,args=getopt.getopt(sys.argv[1:],'twl')
if args:
[infile]=args
s=open(infile,'r').read()
else:
s=sys.stdin.read()
if opts:
if filter(lambda o: o[0]=='-w', opts):
print 'Content-Type: text/html\n'
if filter(lambda o: o[0]=='-l', opts):
import locale
locale.setlocale(locale.LC_ALL,"")
if s[:2]=='#!':
s=re.sub('^#![^\n]+','',s)
mo = re.compile('([\0-\n]*\n)').match(s)
if mo is not None:
s = s[len(mo.group(0)) :]
s=str(html_with_references(s))
if s[:4]=='<h1>':
t=s[4: s.find('</h1>')]
s='''<html><head><title>%s</title>
</head><body>
%s
</body></html>
''' % (t,s)
print s
else:
print html_with_references(s)
if __name__=="__main__": main()
=== Added File zopeproducts/zwiki/renderer/StructuredText/DocBookClass.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
class DocBookClass:
element_types={
'#text': '_text',
'StructuredTextDocument': 'document',
'StructuredTextParagraph': 'paragraph',
'StructuredTextExample': 'example',
'StructuredTextBullet': 'bullet',
'StructuredTextNumbered': 'numbered',
'StructuredTextDescription': 'description',
'StructuredTextDescriptionTitle': 'descriptionTitle',
'StructuredTextDescriptionBody': 'descriptionBody',
'StructuredTextSection': 'section',
'StructuredTextSectionTitle': 'sectionTitle',
'StructuredTextLiteral': 'literal',
'StructuredTextEmphasis': 'emphasis',
'StructuredTextStrong': 'strong',
'StructuredTextLink': 'link',
'StructuredTextXref': 'xref',
'StructuredTextSGML': 'sgml',
}
def dispatch(self, doc, level, output):
getattr(self, self.element_types[doc.getNodeName()])(doc, level, output)
def __call__(self, doc, level=1):
r=[]
self.dispatch(doc, level-1, r.append)
return ''.join(r)
def _text(self, doc, level, output):
if doc.getNodeName() == 'StructuredTextLiteral':
output(doc.getNodeValue())
else:
output(doc.getNodeValue().lstrip())
def document(self, doc, level, output):
output('<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">\n')
output('<book>\n')
children=doc.getChildNodes()
if (children and
children[0].getNodeName() == 'StructuredTextSection'):
output('<title>%s</title>' % children[0].getChildNodes()[0].getNodeValue())
for c in children:
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</book>\n')
def section(self, doc, level, output):
output('\n<section>\n')
children=doc.getChildNodes()
for c in children:
getattr(self, self.element_types[c.getNodeName()])(c, level+1, output)
output('\n</section>\n')
def sectionTitle(self, doc, level, output):
output('<title>')
for c in doc.getChildNodes():
try:
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
except:
print "failed", c.getNodeName(), c
output('</title>\n')
def description(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('<variablelist>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
if n is None or n.getNodeName() is not doc.getNodeName():
output('</variablelist>\n')
def descriptionTitle(self, doc, level, output):
output('<varlistentry><term>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</term>\n')
def descriptionBody(self, doc, level, output):
output('<listitem><para>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</para></listitem>\n')
output('</varlistentry>\n')
def bullet(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('<itemizedlist>\n')
output('<listitem><para>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
output('</para></listitem>\n')
if n is None or n.getNodeName() is not doc.getNodeName():
output('</itemizedlist>\n')
def numbered(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('<orderedlist>\n')
output('<listitem><para>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
output('</para></listitem>\n')
if n is None or n.getNodeName() is not doc.getNodeName():
output('</orderedlist>\n')
def example(self, doc, level, output):
i=0
for c in doc.getChildNodes():
if i==0:
output('<programlisting>\n<![CDATA[\n')
##
## eek. A ']]>' in your body will break this...
##
output(prestrip(c.getNodeValue()))
output('\n]]></programlisting>\n')
else:
getattr(self, self.element_types[c.getNodeName()])(
c, level, output)
def paragraph(self, doc, level, output):
output('<para>\n\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(
c, level, output)
output('</para>\n\n')
def link(self, doc, level, output):
output('<ulink url="%s">' % doc.href)
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</ulink>')
def emphasis(self, doc, level, output):
output('<emphasis>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</emphasis> ')
def literal(self, doc, level, output):
output('<literal>')
for c in doc.getChildNodes():
output(c.getNodeValue())
output('</literal>')
def strong(self, doc, level, output):
output('<emphasis>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</emphasis>')
def xref(self, doc, level, output):
output('<xref linkend="%s"/>' % doc.getNodeValue())
def sgml(self, doc, level, output):
output(doc.getNodeValue())
def prestrip(v):
v=v.replace( '\r\n', '\n')
v=v.replace( '\r', '\n')
v=v.replace( '\t', ' ')
lines=v.split('\n')
indent=len(lines[0])
for line in lines:
if not len(line): continue
i=len(line)-len(line.lstrip())
if i < indent:
indent=i
nlines=[]
for line in lines:
nlines.append(line[indent:])
return '\n'.join(nlines, '\n')
class DocBookChapter(DocBookClass):
def document(self, doc, level, output):
output('<chapter>\n')
children=doc.getChildNodes()
if (children and
children[0].getNodeName() == 'StructuredTextSection'):
output('<title>%s</title>' % children[0].getChildNodes()[0].getNodeValue())
for c in children[0].getChildNodes()[1:]:
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</chapter>\n')
ets = DocBookClass.element_types
ets.update({'StructuredTextImage': 'image'})
class DocBookChapterWithFigures(DocBookChapter):
element_types = ets
def image(self, doc, level, output):
if hasattr(doc, 'key'):
output('<figure id="%s"><title>%s</title>\n' % (doc.key, doc.getNodeValue()) )
else:
output('<figure><title>%s</title>\n' % doc.getNodeValue())
## for c in doc.getChildNodes():
## getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('<graphic fileref="%s"></graphic>\n</figure>\n' % doc.href)
class DocBookArticle(DocBookClass):
def document(self, doc, level, output):
output('<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook V4.1//EN">\n')
output('<article>\n')
children=doc.getChildNodes()
if (children and
children[0].getNodeName() == 'StructuredTextSection'):
output('<articleinfo>\n<title>%s</title>\n</articleinfo>\n' %
children[0].getChildNodes()[0].getNodeValue())
for c in children:
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</article>\n')
class DocBookBook:
def __init__(self, title=''):
self.title = title
self.chapters = []
def addChapter(self, chapter):
self.chapters.append(chapter)
def read(self):
out = '<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">\n<book>\n'
out = out + '<title>%s</title>\n' % self.title
for chapter in self.chapters:
out = out + chapter + '\n</book>\n'
return out
def __str__(self):
return self.read()
=== Added File zopeproducts/zwiki/renderer/StructuredText/DocumentClass.py === (846/946 lines abridged)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import re, ST, STDOM
from STletters import letters, digits, literal_punc, under_punc,\
strongem_punc, phrase_delimiters,dbl_quoted_punc
from types import StringType, UnicodeType, ListType
StringTypes = (StringType, UnicodeType)
def flatten(obj, append):
if obj.getNodeType()==STDOM.TEXT_NODE:
append(obj.getNodeValue())
else:
for child in obj.getChildNodes():
flatten(child, append)
class StructuredTextExample(ST.StructuredTextParagraph):
"""Represents a section of document with literal text, as for examples"""
def __init__(self, subs, **kw):
t=[]
a=t.append
for s in subs:
flatten(s, a)
ST.StructuredTextParagraph.__init__(self, '\n\n'.join(t), (), **kw)
def getColorizableTexts(self): return ()
def setColorizableTexts(self, src): pass # never color examples
class StructuredTextBullet(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextNumbered(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
class StructuredTextDescriptionTitle(ST.StructuredTextParagraph):
"""Represents a section of a document with a title and a body"""
[-=- -=- -=- 846 lines omitted -=- -=- -=-]
def doc_href(self, s, expr, punctuation=re.compile(r"[\,\.\?\!\;]+").match):
r=expr(s)
if r:
# need to grab the href part and the
# beginning part
start,e = r.span(1)
name = s[start:e]
name = name.replace('"','',2)
#start = start + 1
st,end = r.span(3)
if punctuation(s[end-1:end]):
end = end -1
link = s[st:end]
#end = end - 1
# name is the href title, link is the target
# of the href
return (StructuredTextLink(name, href=link),
start, end)
#return (StructuredTextLink(s[start:end], href=s[start:end]),
# start, end)
else:
return None
def doc_sgml(self,s,expr=re.compile(r"\<[%s0-9\.\=\'\"\:\/\-\#\+\s\*]+\>" % letters).search):
"""
SGML text is ignored and outputed as-is
"""
r = expr(s)
if r:
start,end = r.span()
text = s[start:end]
return (StructuredTextSGML(text),start,end)
else:
return None
def doc_xref(self, s,
expr = re.compile('\[([%s0-9\-.:/;,\n\r\~]+)\]' % letters).search
):
r = expr(s)
if r:
start, end = r.span(1)
return (StructuredTextXref(s[start:end]), start-1, end+1)
else:
return None
=== Added File zopeproducts/zwiki/renderer/StructuredText/DocumentWithImages.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import re
from DocumentClass import *
class StructuredTextImage(StructuredTextMarkup):
"A simple embedded image"
class DocumentWithImages(DocumentClass):
"""
"""
text_types = [
'doc_img',
] + DocumentClass.text_types
def doc_img(
self, s,
expr1=re.compile('\"([ _a-zA-Z0-9*.:/;,\-\n\~]+)\":img:([a-zA-Z0-9\_\-.:/;,\n\~]+)').search,
expr2=re.compile('\"([ _a-zA-Z0-9*.:/;,\-\n\~]+)\":img:([a-zA-Z0-9\_\-.:/;,\n\~]+):([a-zA-Z0-9_\-.:/;,\n\~]+)').search
):
r = expr2(s)
if r:
# Warning: the regex are getting confused when the string after :img:
# is an URL containing ":" (Collector #2276)
# Ugly workaround: check if have an absolute URL here. Not a cool solution,
# but it works !
if not r.group(2) in ['http','file','ftp']:
startt, endt = r.span(1)
startk, endk = r.span(2)
starth, endh = r.span(3)
start, end = r.span()
key = s[startk:endk]
return (StructuredTextImage(s[startt:endt], href=s[starth:endh], key=s[startk:endk]),
start, end)
r=expr1(s)
if r:
startt, endt = r.span(1)
starth, endh = r.span(2)
start, end = r.span()
return (StructuredTextImage(s[startt:endt], href=s[starth:endh]),
start, end)
return None
=== Added File zopeproducts/zwiki/renderer/StructuredText/HTMLClass.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
from cgi import escape
import re, sys, ST
class HTMLClass:
element_types={
'#text': '_text',
'StructuredTextDocument': 'document',
'StructuredTextParagraph': 'paragraph',
'StructuredTextExample': 'example',
'StructuredTextBullet': 'bullet',
'StructuredTextNumbered': 'numbered',
'StructuredTextDescription': 'description',
'StructuredTextDescriptionTitle': 'descriptionTitle',
'StructuredTextDescriptionBody': 'descriptionBody',
'StructuredTextSection': 'section',
'StructuredTextSectionTitle': 'sectionTitle',
'StructuredTextLiteral': 'literal',
'StructuredTextEmphasis': 'emphasis',
'StructuredTextStrong': 'strong',
'StructuredTextLink': 'link',
'StructuredTextXref': 'xref',
'StructuredTextInnerLink':'innerLink',
'StructuredTextNamedLink':'namedLink',
'StructuredTextUnderline':'underline',
'StructuredTextTable':'table',
'StructuredTextSGML':'sgml',
}
def dispatch(self, doc, level, output):
getattr(self, self.element_types[doc.getNodeName()])(doc, level, output)
def __call__(self, doc, level=1, header=1):
r=[]
self.header = header
self.dispatch(doc, level-1, r.append)
return ''.join(r)
def _text(self, doc, level, output):
output(doc.getNodeValue())
def document(self, doc, level, output):
children=doc.getChildNodes()
if self.header:
output('<html>\n')
if (children and
children[0].getNodeName() == 'StructuredTextSection'):
output('<head>\n<title>%s</title>\n</head>\n' %
children[0].getChildNodes()[0].getNodeValue())
output('<body>\n')
for c in children:
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
if self.header:
output('</body>\n')
output('</html>\n')
def section(self, doc, level, output):
children=doc.getChildNodes()
for c in children:
getattr(self, self.element_types[c.getNodeName()])(c, level+1, output)
def sectionTitle(self, doc, level, output):
output('<h%d>' % (level))
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</h%d>\n' % (level))
def description(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('<dl>\n')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
if n is None or n.getNodeName() is not doc.getNodeName():
output('</dl>\n')
def descriptionTitle(self, doc, level, output):
output('<dt>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</dt>\n')
def descriptionBody(self, doc, level, output):
output('<dd>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</dd>\n')
def bullet(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('\n<ul>\n')
output('<li>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
output('</li>\n')
if n is None or n.getNodeName() is not doc.getNodeName():
output('\n</ul>\n')
def numbered(self, doc, level, output):
p=doc.getPreviousSibling()
if p is None or p.getNodeName() is not doc.getNodeName():
output('\n<ol>\n')
output('<li>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
n=doc.getNextSibling()
output('</li>\n')
if n is None or n.getNodeName() is not doc.getNodeName():
output('\n</ol>\n')
def example(self, doc, level, output):
i=0
for c in doc.getChildNodes():
if i==0:
output('\n<pre>\n')
output(escape(c.getNodeValue()))
output('\n</pre>\n')
else:
getattr(self, self.element_types[c.getNodeName()])(
c, level, output)
def paragraph(self, doc, level, output):
output('<p>')
for c in doc.getChildNodes():
if c.getNodeName() in ['StructuredTextParagraph']:
getattr(self, self.element_types[c.getNodeName()])(
c, level, output)
else:
getattr(self, self.element_types[c.getNodeName()])(
c, level, output)
output('</p>\n')
def link(self, doc, level, output):
output('<a href="%s">' % doc.href)
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</a>')
def emphasis(self, doc, level, output):
output('<em>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</em>')
def literal(self, doc, level, output):
output('<code>')
for c in doc.getChildNodes():
output(escape(c.getNodeValue()))
output('</code>')
def strong(self, doc, level, output):
output('<strong>')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('</strong>')
def underline(self, doc, level, output):
output("<u>")
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output("</u>")
def innerLink(self, doc, level, output):
output('<a href="#ref');
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('">[')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output(']</a>')
def namedLink(self, doc, level, output):
output('<a name="ref')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output('">[')
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
output(']</a>')
def sgml(self,doc,level,output):
for c in doc.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
def xref(self, doc, level, output):
val = doc.getNodeValue()
output('<a href="#ref%s">[%s]</a>' % (val, val) )
def table(self,doc,level,output):
"""
A StructuredTextTable holds StructuredTextRow(s) which
holds StructuredTextColumn(s). A StructuredTextColumn
is a type of StructuredTextParagraph and thus holds
the actual data.
"""
output('<table border="1" cellpadding="2">\n')
for row in doc.getRows()[0]:
output("<tr>\n")
for column in row.getColumns()[0]:
if hasattr(column,"getAlign"):
str = '<%s colspan="%s" align="%s" valign="%s">' % (column.getType(),
column.getSpan(),
column.getAlign(),
column.getValign())
else:
str = '<td colspan="%s">' % column.getSpan()
output(str)
for c in column.getChildNodes():
getattr(self, self.element_types[c.getNodeName()])(c, level, output)
if hasattr(column,"getType"):
output("</"+column.getType()+">\n")
else:
output("</td>\n")
output("</tr>\n")
output("</table>\n")
=== Added File zopeproducts/zwiki/renderer/StructuredText/HTMLWithImages.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
from HTMLClass import HTMLClass
ets = HTMLClass.element_types
ets.update({'StructuredTextImage': 'image'})
class HTMLWithImages(HTMLClass):
element_types = ets
def image(self, doc, level, output):
if hasattr(doc, 'key'):
output('<a name="%s"></a>\n' % doc.key)
output('<img src="%s" alt="%s">\n' % (doc.href, doc.getNodeValue()))
if doc.getNodeValue() and hasattr(doc, 'key'):
output('<p><b>Figure %s</b> %s</p>\n' % (doc.key, doc.getNodeValue()))
=== Added File zopeproducts/zwiki/renderer/StructuredText/ST.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import re, STDOM
from types import ListType
#####################################################################
# Updated functions #
#####################################################################
def indention(str,front = re.compile("^\s+").match):
"""
Find the number of leading spaces. If none, return 0.
"""
result = front(str)
if result is not None:
start, end = result.span()
return end-start
else:
return 0 # no leading spaces
def insert(struct, top, level):
"""
find what will be the parant paragraph of
a sentence and return that paragraph's
sub-paragraphs. The new paragraph will be
appended to those sub-paragraphs
"""
#print "struct", struct, top-1
if not top-1 in range(len(struct)):
if struct:
return struct[len(struct)-1].getSubparagraphs()
return struct
run = struct[top-1]
i = 0
while i+1 < level:
run = run.getSubparagraphs()[len(run.getSubparagraphs())-1]
i = i + 1
#print "parent for level ", level, " was => ", run.getColorizableTexts()
return run.getSubparagraphs()
def display(struct):
"""
runs through the structure and prints out
the paragraphs. If the insertion works
correctly, display's results should mimic
the orignal paragraphs.
"""
if struct.getColorizableTexts():
print join(struct.getColorizableTexts()),"\n"
if struct.getSubparagraphs():
for x in struct.getSubparagraphs():
display(x)
def display2(struct):
"""
runs through the structure and prints out
the paragraphs. If the insertion works
correctly, display's results should mimic
the orignal paragraphs.
"""
if struct.getNodeValue():
print struct.getNodeValue(),"\n"
if struct.getSubparagraphs():
for x in struct.getSubparagraphs():
display(x)
def findlevel(levels,indent):
"""
remove all level information of levels
with a greater level of indentation.
Then return which level should insert this
paragraph
"""
keys = levels.keys()
for key in keys:
if levels[key] > indent:
del(levels[key])
keys = levels.keys()
if not(keys):
return 0
else:
for key in keys:
if levels[key] == indent:
return key
highest = 0
for key in keys:
if key > highest:
highest = key
return highest-1
para_delim = r'(\n\s*\n|\r\n\s*\r\n)' # UNIX or DOS line endings, respectively
#####################################################################
# Golly, the capitalization of this function always makes me think it's a class
def StructuredText(paragraphs, delimiter=re.compile(para_delim)):
"""
StructuredText accepts paragraphs, which is a list of
lines to be parsed. StructuredText creates a structure
which mimics the structure of the paragraphs.
Structure => [paragraph,[sub-paragraphs]]
"""
currentlevel = 0
currentindent = 0
levels = {0:0}
level = 0 # which header are we under
struct = [] # the structure to be returned
run = struct
paragraphs = paragraphs.expandtabs()
paragraphs = '%s%s%s' % ('\n\n', paragraphs, '\n\n')
paragraphs = delimiter.split(paragraphs)
paragraphs = [ x for x in paragraphs if x.strip() ]
if not paragraphs: return StructuredTextDocument()
ind = [] # structure based on indention levels
for paragraph in paragraphs:
ind.append([indention(paragraph), paragraph])
currentindent = indention(paragraphs[0])
levels[0] = currentindent
#############################################################
# updated #
#############################################################
for indent,paragraph in ind :
if indent == 0:
level = level + 1
currentlevel = 0
currentindent = 0
levels = {0:0}
struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel))
elif indent > currentindent:
currentlevel = currentlevel + 1
currentindent = indent
levels[currentlevel] = indent
run = insert(struct,level,currentlevel)
run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel))
elif indent < currentindent:
result = findlevel(levels,indent)
if result > 0:
currentlevel = result
currentindent = indent
if not level:
struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel))
else:
run = insert(struct,level,currentlevel)
run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel))
else:
if insert(struct,level,currentlevel):
run = insert(struct,level,currentlevel)
else:
run = struct
currentindent = indent
run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel))
return StructuredTextDocument(struct)
Basic = StructuredText
class StructuredTextParagraph(STDOM.Element):
indent=0
def __init__(self, src, subs=None, **kw):
if subs is None: subs=[]
self._src=src
self._subs=list(subs)
self._attributes=kw.keys()
for k, v in kw.items(): setattr(self, k, v)
def getChildren(self):
src=self._src
if not isinstance(src, ListType): src=[src]
return src+self._subs
def getAttribute(self, name):
return getattr(self, name, None)
def getAttributeNode(self, name):
if hasattr(self, name):
return STDOM.Attr(name, getattr(self, name))
else:
return None
def getAttributes(self):
d={}
for a in self._attributes:
d[a]=getattr(self, a, '')
return STDOM.NamedNodeMap(d)
def getSubparagraphs(self):
return self._subs
def setSubparagraphs(self, subs):
self._subs=subs
def getColorizableTexts(self):
return (self._src,)
def setColorizableTexts(self, src):
self._src=src[0]
def __repr__(self):
r=[]; a=r.append
a((' '*(self.indent or 0))+
('%s(' % self.__class__.__name__)
+str(self._src)+', ['
)
for p in self._subs: a(`p`)
a((' '*(self.indent or 0))+'])')
return '\n'.join(r)
"""
create aliases for all above functions in the pythony way.
"""
def _get_Children(self):
return self.getChildren()
def _get_Attribute(self, name):
return self.getAttribute(name)
def _get_AttributeNode(self, name):
return self.getAttributeNode(name)
def _get_Attributes(self):
return self.getAttributes()
def _get_Subparagraphs(self):
return self.getSubparagraphs()
def _set_Subparagraphs(self, subs):
return self.setSubparagraphs(subs)
def _get_ColorizableTexts(self):
return self.getColorizableTexts()
def _set_ColorizableTexts(self, src):
return self.setColorizableTexts(src)
class StructuredTextDocument(StructuredTextParagraph):
"""
A StructuredTextDocument holds StructuredTextParagraphs
as its subparagraphs.
"""
_attributes=()
def __init__(self, subs=None, **kw):
StructuredTextParagraph.__init__(self, '', subs, **kw)
def getChildren(self):
return self._subs
def getColorizableTexts(self):
return ()
def setColorizableTexts(self, src):
pass
def __repr__(self):
r=[]; a=r.append
a('%s([' % self.__class__.__name__)
for p in self._subs: a(`p`+',')
a('])')
return '\n'.join(r)
"""
create aliases for all above functions in the pythony way.
"""
def _get_Children(self):
return self.getChildren()
def _get_ColorizableTexts(self):
return self.getColorizableTexts()
def _set_ColorizableTexts(self, src):
return self.setColorizableTexts(src)
=== Added File zopeproducts/zwiki/renderer/StructuredText/STDOM.py === (550/650 lines abridged)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""
DOM implementation in StructuredText : Read-Only methods
All standard Zope objects support DOM to a limited extent.
"""
from types import StringType, UnicodeType
StringTypes = (StringType, UnicodeType)
# Node type codes
# ---------------
ELEMENT_NODE = 1
ATTRIBUTE_NODE = 2
TEXT_NODE = 3
CDATA_SECTION_NODE = 4
ENTITY_REFERENCE_NODE = 5
ENTITY_NODE = 6
PROCESSING_INSTRUCTION_NODE = 7
COMMENT_NODE = 8
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
DOCUMENT_FRAGMENT_NODE = 11
NOTATION_NODE = 12
# Exception codes
# ---------------
INDEX_SIZE_ERR = 1
DOMSTRING_SIZE_ERR = 2
HIERARCHY_REQUEST_ERR = 3
WRONG_DOCUMENT_ERR = 4
INVALID_CHARACTER_ERR = 5
NO_DATA_ALLOWED_ERR = 6
NO_MODIFICATION_ALLOWED_ERR = 7
NOT_FOUND_ERR = 8
NOT_SUPPORTED_ERR = 9
INUSE_ATTRIBUTE_ERR = 10
[-=- -=- -=- 550 lines omitted -=- -=- -=-]
def getNodeName(self):
"""
The name of this node, depending on its type
"""
return self.name
def getName(self):
"""
Returns the name of this attribute.
"""
return self.name
def getNodeValue(self):
"""
The value of this node, depending on its type
"""
return self.value
def getNodeType(self):
"""
A code representing the type of the node.
"""
return ATTRIBUTE_NODE
def getSpecified(self):
"""
If this attribute was explicitly given a value in the
original document, this is true; otherwise, it is false.
"""
return self.specified
"""
create aliases for all above functions in the pythony way.
"""
def _get_NodeName(self):
return self.getNodeName()
def _get_Name(self):
return self.getName()
def _get_NodeValue(self):
return self.getNodeValue()
def _get_NodeType(self):
return self.getNodeType()
def _get_Specified(self):
return self.getSpecified()
=== Added File zopeproducts/zwiki/renderer/StructuredText/STNG.txt ===
Using Structured Text
The goal of StructuredText is to make it possible to express
structured text using a relatively simple plain text format. Simple
structures, like bullets or headings are indicated through
conventions that are natural, for some definition of
"natural". Hierarchical structures are indicated through
indentation. The use of indentation to express hierarchical
structure is inspired by the Python programming language.
Use of StructuredText consists of one to three logical steps. In the
first step, a text string is converted to a network of objects using
the 'StructuredText.Basic' facility, as in the following
example::
raw=open("mydocument.txt").read()
import StructuredText
st=StructuredText.Basic(raw)
The output of 'StructuredText.Basic' is simply a
StructuredTextDocument object containing StructuredTextParagraph
objects arranged in a hierarchy. Paragraphs are delimited by strings
of two or more whitespace characters beginning and ending with
newline characters. Hierarchy is indicated by indentation. The
indentation of a paragraph is the minimum number of leading spaces
in a line containing non-white-space characters after converting tab
characters to spaces (assuming a tab stop every eight characters).
StructuredTextNode objects support the read-only subset of the
Document Object Model (DOM) API. It should be possible to process
'StructuredTextNode' hierarchies using XML tools such as XSLT.
The second step in using StructuredText is to apply additional
structuring rules based on text content. A variety of differentText
rules can be used. Typically, these are used to implement a
structured text language for producing documents, but any sort of
structured text language could be implemented in the second
step. For example, it is possible to use StructuredText to implement
structured text formats for representing structured data. The second
step, which could consist of multiple processing steps, is
performed by processing, or "coloring", the hierarchy of generic
StructuredTextParagraph objects into a network of more specialized
objects. Typically, the objects produced should also implement the DOM
API to allow processing with XML tools.
A document processor is provided to convert a StructuredTextDocument
object containing only StructuredStructuredTextParagraph objects
into a StructuredTextDocument object containing a richer collection
of objects such as bullets, headings, emphasis, and so on using
hints in the text. Hints are selected based on conventions of the
sort typically seen in electronic mail or news-group postings. It
should be noted, however, that these conventions are somewhat
culturally dependent, fortunately, the document processor is easily
customized to implement alternative rules. Here's an example of
using the DOC processor to convert the output of the previous example::
doc=StructuredText.Document(st)
The final step is to process the colored networks produced from the
second step to produce additional outputs. The final step could be
performed by Python programs, or by XML tools. A Python outputter is
provided for the document processor output that produces Hypertext Markup
Language (HTML) text::
html=StructuredText.HTML(doc)
Customizing the document processor
The document processor is driven by two tables. The first table,
named 'paragraph_types', is a sequence of callable objects or method
names for coloring paragraphs. If a table entry is a string, then it
is the name of a method of the document processor to be used. For
each input paragraph, the objects in the table are called until one
returns a value (not 'None'). The value returned replaces the
original input paragraph in the output. If none of the objects in
the paragraph types table return a value, then a copy of the
original paragraph is used. The new object returned by calling a
paragraph type should implement the ReadOnlyDOM,
StructuredTextColorizable, and StructuredTextSubparagraphContainer
interfaces. See the 'Document.py' source file for examples.
A paragraph type may return a list or tuple of replacement
paragraphs, this allowing a paragraph to be split into multiple
paragraphs.
The second table, 'text_types', is a sequence of callable objects or
method names for coloring text. The callable objects in this table
are used in sequence to transform the input text into new text or
objects. The callable objects are passed a string and return
nothing ('None') or a three-element tuple consisting of:
- a replacement object,
- a starting position, and
- an ending position
The text from the starting position is (logically) replaced with the
replacement object. The replacement object is typically an object
that implements that implements the ReadOnlyDOM, and
StructuredTextColorizable interfaces. The replacement object can
also be a string or a list of strings or objects. Replacement is
done from beginning to end and text after the replacement ending
position will be passed to the character type objects for processing.
Example: adding wiki links
We want to add support for Wiki links. A Wiki link is a string of
text containing mixed-case letters, such that at least two of the
letters are upper case and such that the first letter is upper case.
=== Added File zopeproducts/zwiki/renderer/StructuredText/STletters.py ===
import string
def punc_func(exclude):
punc = r''
for char in string.punctuation:
if char not in exclude:
punc = punc + r'\%s' % char
return punc
digits = string.digits
letters = string.letters
literal_punc = punc_func("'")
dbl_quoted_punc = punc_func("\"")
strongem_punc = punc_func('*')
under_punc = punc_func('_<>')
phrase_delimiters = r'\s\.\,\?\/\!\&\(\)'
=== Added File zopeproducts/zwiki/renderer/StructuredText/StructuredText.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
""" Alias module for StructuredTextClassic compatibility which makes
use of StructuredTextNG """
import HTMLClass, DocumentClass
import DocumentWithImages, HTMLWithImages
from ST import Basic
import re, sys
from STletters import letters
Document = DocumentClass.DocumentClass()
HTMLNG = HTMLClass.HTMLClass()
DocumentImages = DocumentWithImages.DocumentWithImages()
HTMLNGImages = HTMLWithImages.HTMLWithImages()
def HTML(aStructuredString, level=1, header=1):
st = Basic(aStructuredString)
doc = DocumentImages(st)
return HTMLNGImages(doc,header=header,level=level)
def StructuredText(aStructuredString, level=1):
return HTML(aStructuredString,level)
def html_with_references(text, level=1, header=1):
text = re.sub(
r'[\000\n]\.\. \[([0-9_%s-]+)\]' % letters,
r'\n <a name="\1">[\1]</a>',
text)
text = re.sub(
r'([\000- ,])\[(?P<ref>[0-9_%s-]+)\]([\000- ,.:])' % letters,
r'\1<a href="#\2">[\2]</a>\3',
text)
text = re.sub(
r'([\000- ,])\[([^]]+)\.html\]([\000- ,.:])',
r'\1<a href="\2.html">[\2]</a>\3',
text)
return HTML(text,level=level,header=header)
def html_quote(v,
character_entities=(
(re.compile('&'), '&'),
(re.compile("<"), '<' ),
(re.compile(">"), '>' ),
(re.compile('"'), '"')
)): #"
text=str(v)
for re,name in character_entities:
text=re.sub(name,text)
return text
if __name__=='__main__':
import getopt
opts,args = getopt.getopt(sys.argv[1:],'',[])
for k,v in opts:
pass
for f in args:
print HTML(open(f).read())
=== Added File zopeproducts/zwiki/renderer/StructuredText/__init__.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import HTMLClass, DocumentClass
import ClassicDocumentClass
from StructuredText import html_with_references, HTML, html_quote
from ST import Basic
import DocBookClass
import HTMLWithImages
from types import StringType, UnicodeType
import DocumentWithImages
ClassicHTML=HTML
HTMLNG=HTMLClass.HTMLClass()
def HTML(src, level=1):
if isinstance(src, StringType) or isinstance(src, UnicodeType):
return ClassicHTML(src, level)
return HTMLNG(src, level)
Classic=ClassicDocumentClass.DocumentClass()
Document=DocumentClass.DocumentClass()
DocumentWithImages=DocumentWithImages.DocumentWithImages()
HTMLWithImages=HTMLWithImages.HTMLWithImages()
DocBookBook=DocBookClass.DocBookBook()
DocBookChapter=DocBookClass.DocBookChapter()
DocBookChapterWithFigures=DocBookClass.DocBookChapterWithFigures()
DocBookArticle=DocBookClass.DocBookArticle()
=== Added File zopeproducts/zwiki/renderer/StructuredText/ts_regex.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Provide a thread-safe interface to regex
"""
import regex, regsub #, Sync
from regex import *
from regsub import split, sub, gsub, splitx, capwords
try:
import thread
except:
class allocate_lock:
def acquire(*args): pass
def release(*args): pass
else:
class SafeFunction:
_l=thread.allocate_lock()
_a=_l.acquire
_r=_l.release
def __init__(self, f):
self._f=f
def __call__(self, *args, **kw):
self._a()
try: return self._f(*args, **kw)
finally: self._r()
split=SafeFunction(split)
sub=SafeFunction(sub)
gsub=SafeFunction(gsub)
splitx=SafeFunction(splitx)
capwords=SafeFunction(capwords)
allocate_lock=thread.allocate_lock
class compile:
_r=None
groupindex=None
def __init__(self, *args):
self._r=r=regex(*compile, **args)
self._init(r)
def _init(self, r):
lock=allocate_lock()
self.__a=lock.acquire
self.__r=lock.release
self.translate=r.translate
self.givenpat=r.givenpat
self.realpat=r.realpat
def match(self, string, pos=0):
self.__a()
try: return self._r.match(string, pos)
finally: self.__r()
def search(self, string, pos=0):
self.__a()
try: return self._r.search(string, pos)
finally: self.__r()
def search_group(self, str, group, pos=0):
"""Search a string for a pattern.
If the pattern was not found, then None is returned,
otherwise, the location where the pattern was found,
as well as any specified group are returned.
"""
self.__a()
try:
r=self._r
l=r.search(str, pos)
if l < 0: return None
return l, r.group(*group)
finally: self.__r()
def match_group(self, str, group, pos=0):
"""Match a pattern against a string
If the string does not match the pattern, then None is
returned, otherwise, the length of the match, as well
as any specified group are returned.
"""
self.__a()
try:
r=self._r
l=r.match(str, pos)
if l < 0: return None
return l, r.group(*group)
finally: self.__r()
def search_regs(self, str, pos=0):
"""Search a string for a pattern.
If the pattern was not found, then None is returned,
otherwise, the 'regs' attribute of the expression is
returned.
"""
self.__a()
try:
r=self._r
r.search(str, pos)
return r.regs
finally: self.__r()
def match_regs(self, str, pos=0):
"""Match a pattern against a string
If the string does not match the pattern, then None is
returned, otherwise, the 'regs' attribute of the expression is
returned.
"""
self.__a()
try:
r=self._r
r.match(str, pos)
return r.regs
finally: self.__r()
class symcomp(compile):
def __init__(self, *args):
self._r=r=regex.symcomp(*args)
self._init(r)
self.groupindex=r.groupindex