1+ class Handler :
2+ """
3+ An object that handles method calls from the Parser.
4+
5+ The Parser will call the start() and end() methods at the
6+ beginning of each block, with the proper block name as a
7+ parameter. The sub() method will be used in regular expression
8+ substitution. When called with a name such as 'emphasis', it will
9+ return a proper substitution function.
10+ """
11+ def callback (self , prefix , name , * args ):
12+ method = getattr (self , prefix + name , None )
13+ if callable (method ): return method (* args )
14+ def start (self , name ):
15+ self .callback ('start_' , name )
16+ def end (self , name ):
17+ self .callback ('end_' , name )
18+ def sub (self , name ):
19+ def substitution (match ):
20+ result = self .callback ('sub_' , name , match )
21+ if result is None : match .group (0 )
22+ return result
23+ return substitution
24+
25+ class HTMLRenderer (Handler ):
26+ """
27+ A specific handler used for rendering HTML.
28+
29+ The methods in HTMLRenderer are accessed from the superclass
30+ Handler's start(), end(), and sub() methods. They implement basic
31+ markup as used in HTML documents.
32+ """
33+ def start_document (self ):
34+ print '<html><head><title>...</title></head><body>'
35+ def end_document (self ):
36+ print '</body></html>'
37+ def start_paragraph (self ):
38+ print '<p>'
39+ def end_paragraph (self ):
40+ print '</p>'
41+ def start_heading (self ):
42+ print '<h2>'
43+ def end_heading (self ):
44+ print '</h2>'
45+ def start_list (self ):
46+ print '<ul>'
47+ def end_list (self ):
48+ print '</ul>'
49+ def start_listitem (self ):
50+ print '<li>'
51+ def end_listitem (self ):
52+ print '</li>'
53+ def start_title (self ):
54+ print '<h1>'
55+ def end_title (self ):
56+ print '</h1>'
57+ def sub_emphasis (self , match ):
58+ return '<em>%s</em>' % match .group (1 )
59+ def sub_url (self , match ):
60+ return '<a href="%s">%s</a>' % (match .group (1 ), match .group (1 ))
61+ def sub_mail (self , match ):
62+ return '<a href="mailto:%s">%s</a>' % (match .group (1 ), match .group (1 ))
63+ def feed (self , data ):
64+ print data
0 commit comments