Sanely deprecate StructuredText by making it a facade of zope.structuredtext.

parent a91bbc42
......@@ -11,8 +11,10 @@
#
##############################################################################
import re, ST, STDOM
from STletters import letters
import re
from zope.structuredtext import stng as ST
from zope.structuredtext import stdom as STDOM
from zope.structuredtext.stletters import letters
from types import StringType, UnicodeType, ListType
StringTypes = (StringType, UnicodeType)
......
......@@ -133,6 +133,12 @@ Special symbology is used to indicate special constructs:
'''
import warnings
warnings.warn('The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext instead.',
DeprecationWarning, stacklevel=2)
import ts_regex
import string, re
......
This diff is collapsed.
This diff is collapsed.
......@@ -11,32 +11,15 @@
#
##############################################################################
import re
from DocumentClass import *
class StructuredTextImage(StructuredTextMarkup):
"A simple embedded image"
class DocumentWithImages(DocumentClass):
""" Document with images """
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,
):
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
from zope.structuredtext.stng import StructuredTextImage
from zope.structuredtext.document import DocumentWithImages
from zope.deprecation import deprecated
deprecated("StructuredTextImage",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stng.StructuredTextImage '
'instead.')
deprecated("DocumentWithImages",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.document.DocumentWithImages '
'instead.')
......@@ -11,227 +11,8 @@
#
##############################################################################
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):
node_name = doc.getNodeName()
element_type = self.element_types[node_name]
element_method = getattr(self, element_type)
element_method(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:
self.dispatch(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:
self.dispatch(c, level+1, output)
def sectionTitle(self, doc, level, output):
output('<h%d>' % (level))
for c in doc.getChildNodes():
self.dispatch(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():
self.dispatch(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():
self.dispatch(c, level, output)
output('</dt>\n')
def descriptionBody(self, doc, level, output):
output('<dd>')
for c in doc.getChildNodes():
self.dispatch(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():
self.dispatch(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():
self.dispatch(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:
self.dispatch(c, level, output)
def paragraph(self, doc, level, output):
output('<p>')
for c in doc.getChildNodes():
if c.getNodeName() in ['StructuredTextParagraph']:
self.dispatch(c, level, output)
else:
self.dispatch(c, level, output)
output('</p>\n')
def link(self, doc, level, output):
output('<a href="%s">' % doc.href)
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output('</a>')
def emphasis(self, doc, level, output):
output('<em>')
for c in doc.getChildNodes():
self.dispatch(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():
self.dispatch(c, level, output)
output('</strong>')
def underline(self, doc, level, output):
output("<u>")
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output("</u>")
def innerLink(self, doc, level, output):
output('<a href="#ref');
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output('">[')
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output(']</a>')
def namedLink(self, doc, level, output):
output('<a name="ref')
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output('">[')
for c in doc.getChildNodes():
self.dispatch(c, level, output)
output(']</a>')
def sgml(self,doc,level,output):
for c in doc.getChildNodes():
self.dispatch(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():
self.dispatch(c, level, output)
if hasattr(column,"getType"):
output("</"+column.getType()+">\n")
else:
output("</td>\n")
output("</tr>\n")
output("</table>\n")
from zope.structuredtext.html import HTML as HTMLClass
from zope.deprecation import deprecated
deprecated("HTMLClass",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.html.HTML instead.')
......@@ -11,20 +11,9 @@
#
##############################################################################
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()))
from zope.structuredtext.html import HTMLWithImages
from zope.deprecation import deprecated
deprecated("HTMLWithImages",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.html.HTMLWithImages '
'instead.')
......@@ -11,288 +11,23 @@
#
##############################################################################
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)
from zope.structuredtext.stng import \
indention, insert, display, display2, findlevel
from zope.structuredtext.stng import structurize as StructuredText
from zope.structuredtext.stng import \
StructuredTextParagraph, StructuredTextDocument
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)
from zope.deprecation import deprecated
deprecated(("StructuredText", "Basic"),
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stng.structurize '
'instead.')
deprecated("StructuredTextParagraph",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stng.StructuredTextParagraph '
'instead.')
deprecated("StructuredTextDocument",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stng.StructuredTextDocument '
'instead.')
This diff is collapsed.
Using Structured Text
WARNING! The 'StructuredText' package has been deprecated and will
be removed in Zope 2.12. Use 'zope.structuredtext' instead.
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
......@@ -108,9 +111,3 @@ 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.
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\.\,\?\/\!\&\(\)'
......@@ -10,49 +10,21 @@
# 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)
"""Alias module for StructuredTextClassic compatibility which makes
use of StructuredTextNG"""
import re
from zope.structuredtext import stx2html as HTML
from zope.structuredtext import stx2htmlWithReferences as html_with_references
StructuredText = HTML
from zope.deprecation import deprecated
deprecated(("HTML, StructuredText"),
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stx2html instead.')
deprecated("html_with_references",
'The StructuredText package is deprecated and will be removed '
'in Zope 2.12. Use zope.structuredtext.stx2htmlWithReferences '
'instead.')
def html_quote(v,
character_entities=(
......@@ -66,7 +38,6 @@ def html_quote(v,
text=re.sub(name,text)
return text
if __name__=='__main__':
import getopt
......
......@@ -11,36 +11,35 @@
#
##############################################################################
from zope.structuredtext import html, document, docbook
from zope.structuredtext.stng import structurize as Basic
import warnings
warnings.warn('Using StructuredText is deprecated (will be removed in Zope '
'2.12). Instead use zope.structuredtext.',
DeprecationWarning,
stacklevel=2)
from StructuredText import html_quote
from zope.structuredtext import stx2html as HTML
from zope.structuredtext import stx2htmlWithReferences as html_with_references
from types import StringType, UnicodeType
# BBB -- 2006/01/08 -- Remove in Zope 2.12
import sys
import zope.structuredtext.stletters
import zope.structuredtext.stdom
sys.modules['StructuredText.STletters'] = zope.structuredtext.stletters
sys.modules['StructuredText.STDOM'] = zope.structuredtext.stdom
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
Classic = ClassicDocumentClass.DocumentClass()
Document = document.Document()
DocumentWithImages = document.DocumentWithImages()
HTMLWithImages = html.HTMLWithImages()
ClassicHTML = html.HTML
HTMLNG = html.HTML()
ClassicHTML=HTML
HTMLNG=HTMLClass.HTMLClass()
DocBookBook = docbook.DocBookBook()
DocBookChapter = docbook.DocBookChapter()
DocBookChapterWithFigures = docbook.DocBookChapterWithFigures()
DocBookArticle = docbook.DocBookArticle()
def HTML(src, level=1):
if isinstance(src, StringType) or isinstance(src, UnicodeType):
if isinstance(src, basestring):
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()
......@@ -11,6 +11,7 @@
#
##############################################################################
import zope.deprecation
from StructuredText import ST
from StructuredText import DocumentClass
from StructuredText import ClassicDocumentClass
......@@ -46,6 +47,12 @@ def readFile(dirname,fname):
class StructuredTextTests(unittest.TestCase):
def setUp(self):
zope.deprecation.__show__.off()
def tearDown(self):
zope.deprecation.__show__.on()
def testStructuredText(self):
""" testing StructuredText """
......@@ -134,6 +141,12 @@ class StructuredTextTests(unittest.TestCase):
class BasicTests(unittest.TestCase):
def setUp(self):
zope.deprecation.__show__.off()
def tearDown(self):
zope.deprecation.__show__.on()
def _test(self,stxtxt , expected):
if not isinstance(stxtxt, UnicodeType):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment