4
# $LastChangedDate: 2005-05-28 12:14:08 +0100 (Sat, 28 May 2005) $
5
# $LastChangedBy: fuzzyman $
6
# $HeadURL: https://svn.rest2web.python-hosting.com/trunk/rest2web.py $
7
# $LastChangedRevision: 28 $
10
# http://www.voidspace.org.uk/python/rest2web
12
# Adapted from macros.py for Firedrop2 by Hans Nowak
13
# http://zephyrfalcon.org
15
# Copyright Michael Foord, 2004 & 2005.
16
# Released subject to the BSD License
17
# Please see http://www.voidspace.org.uk/python/license.shtml
19
# For information about bugfixes, updates, and support,
20
# please join the Pythonutils mailing list.
21
# http://groups.google.com/group/pythonutils/
22
# Comments, suggestions, and bug reports, welcome.
23
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
24
# E-mail fuzzyman@voidspace.org.uk
26
# FIXME: Sort smiley stuff....
28
smiley_path, smiley_url = 'smilies', '/smilies/'
31
adblock = ' <!--#include virtual="/includes/adblock.shtml" -->'
32
hiddennetwork = ' <!--#include virtual="/includes/_hiddennetwork.shtml" -->'
42
def _set_uservalues(n, u):
43
"""Set the namespace and uservalues for the page."""
49
##sys.__stdout__.write(os.getcwd())
51
# curlyl and curlyr is a way of including literal
52
# curly brackets in pages
59
# {emoticon;name} e.g. {emoticon;smile}
62
Return a link to a named gif file
63
in the emoticons/ folder.
66
if q in ('movpy', 'firedrop2'):
67
return '<img src="emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
69
return '<img src="/emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
72
def acronym(acronym, meaning=None):
74
Return the HTML for an acronym.
77
# will raise a KeyError if the acronym isn't found
78
meaning = acronyms[acronym.lower()]
79
return '<acronym title="%s">%s</acronym>' % (meaning, acronym)
82
# a dictionary of standard acronyms
83
# keys should be lowercase
85
'wysiwyg': 'What You See Is What You Get',
86
'html': 'HyperText Markup Language',
87
'xml': 'eXtensible Markup Language',
88
'xhtml': 'eXtensible HyperText Markup Language',
89
'rest': 'ReStructuredText',
90
'css': 'Cascading Style Sheets',
91
'ie': 'Internet Exploder',
92
'ide': 'Integrated Development Environment',
93
'afaik': 'As Far as I Know',
94
'ianal': 'I am not a Lawyer',
95
'ssi': 'Server Side Includes',
96
'cgi': 'Common Gateway Interface',
97
'lol': 'Laughing Out Loud',
98
'rotfl': 'Roll On the Floor Laughing',
99
'http': 'HyperText Transfer Protocol',
100
'ascii': 'American Standard Code for Information Interchange',
101
'gui': 'Graphical User Interface',
102
'cli': 'Command Line Interface',
103
'pda': 'Personal Digital Assistant',
104
'rtfm': 'Read the Manual',
105
'ftp': 'File Transfer Protocol',
106
'nntp': 'Network News Transfer Protocol',
107
'uk': 'United Kingdom',
108
'pc': 'Personal Computer',
109
'url': 'Uniform Resource Locator',
110
'uri': 'Uniform Resource Identifier',
111
'tcp/ip': 'Transport Control Protocol/Internet Protocol',
112
'udp': 'User Data Paragram',
113
'yagni': 'You Aint Gonna Need It',
116
def include(filename, escape='False'):
118
Include a file in the page.
121
data = open(filename, 'r').read()
122
if escape.lower() not in ['false', 'off', '0', 'no']:
123
# FIXME: Should we check for invalid options and raise an error ?
124
data = data.replace('\r\n', '\n')
125
data = data.replace('\r', '\n')
126
data = data.replace('\n', '<br />\n').replace(' ', ' ')
131
import smiley as smiley_module
135
Attempting to use this without having the smiley module available
136
will raise an ImportError.
138
raise ImportError, "Importing smiley.py failed."
145
The smiley lib is only created on the first run through.
149
smile = smiley_module.lib(smiley_path, smiley_url)
150
s = smile.makehappy(' %s ' % text)
151
s = s.replace('\n', '')
152
return s.replace(' />', ' height="15" width="15" />') # add the height
156
# syntax coloring with Pygments
158
from pygments import highlight
159
from pygments.lexers import get_lexer_by_name
160
from pygments.formatters import HtmlFormatter
162
def colorize(filename):
163
raise ImportError, 'Importing pygments failed.'
165
def open(self, data):
166
raise ImportError, 'Importing pygments failed.'
167
def close(self, *args):
172
lexer_options = dict(
175
formatter_options = dict(
180
def __init__(self, lexer_options=None, formatter_options=None):
181
self.lexer_options = self.lexer_options.copy()
183
self.lexer_options.update(lexer_otions)
184
self.formatter_options = self.formatter_options.copy()
185
if formatter_options:
186
self.formatter_options.update(formatter_otions)
188
def open(self, data):
189
lexer = get_lexer_by_name("python", **self.lexer_options)
190
formatter = HtmlFormatter(**self.formatter_options)
191
return highlight(data, lexer, formatter)
193
def close(self, *args):
196
def colorize(filename):
197
"""Format Python script as syntax coloured HTML.
199
Using the appropriate css it will be nicely colored.
201
Needs the Pygments package.
204
fullname = os.path.join(filename)
205
f = open(fullname, 'r')
209
colorizer = coloring()
210
return colorizer.open(data)
216
return '<a name="%s" id="%s"></a>' % (n, n)
218
def title(text, size=3):
219
"""For titles of a named size"""
220
return '<h%s>%s</h%s>' % (size, text, size)
223
return '<small>%s</small>' % text
225
#############################################################
227
# Anything below this line is specific to Voidspace
228
# and probably not useful (except maybe as examples....)
230
def target_title(target, title, cls='', ):
231
"""Return a title as a target."""
232
t = '<a href="#%s" %s><h2>%s</h2></a>'
234
cls = 'class="%s"' % cls
235
return t % (target, cls, title)
237
def index_title(Title, subtitle=''):
238
"""target_title for voidspace"""
239
a = target_title('index', Title, 'titlelink')
246
For generating Index Tables
248
The first line is the number of columns and the width in pixels.
249
The next line is the summary.
250
The next line is the title.
251
Following lines are either target and title, or just a single value
252
if they are the same.
254
def open(self, data):
255
data = [line.strip() for line in data.split('\n') if line.strip()]
256
cols, width = data.pop(0).split(' ')
258
start = ('<div class="index-table"><table class="index-table"'
259
'border="1" width="%s" summary="%s">')
260
start = start % (width, data.pop(0))
262
out = [start, '<colgroup>']
264
for i in range(cols):
265
out.append('<col width="%s" />' % width)
266
out.append('</colgroup>')
269
out.append('<thead valign="bottom"><tr><th class="head" '
270
'colspan="%s">%s</th></tr></thead>' % (cols, title))
271
out.append('<tbody valign="top">')
275
while i < len(data) -1:
277
val = data[i].split(' ', 1)
281
target = name = val[0]
282
if i and not i % cols:
283
out.append('</tr><tr>')
284
line = '<td><a href="#%s">%s</a></td>'
285
out.append(line %(target, name))
286
for i in range((i+1) % cols):
287
out.append('<td> </td>')
288
out.append('</tr><tr>')
289
for i in range(cols):
290
out.append('<td> </td>')
291
out.append('</tr></tbody></table></div>')
292
return '\n'.join(out)
294
def close(self, *args):
298
_link = "/cgi-bin/voidspace/downman.py?file=%s"
299
def dl(file, text=''):
300
"""Create a download link for downman."""
304
return '<a href="%s">%s</a>' % (link, text)
307
# a dictionary allowing you to dynamically
308
# assign your smiley URL depending on where you're running this
310
_smiley_loc = { 'makedoc': ('smilies', 'smilies/'),
311
'Webstuff Python': ('../makedoc/smilies', '/smilies/'),
312
'General Blog': ('../../makedoc/smilies', '/smilies/'),
313
'building blog': ('../../makedoc/smilies', '/smilies/'),
314
'Techie Blog': ('../../makedoc/smilies', '/smilies/'),
315
'movpy': ('docs_html/images/smilies', 'images/smilies/'),
316
'firedrop2': ('../smilies', 'smilies/'),
317
'branches': ('firedrop2-dist/firedrop2/docs_html/smilies', 'smilies/'),
320
p = os.getcwd().replace('/', '\\')
323
p, q = os.path.split(p)
324
if q in _smiley_loc and 'Python Projects' in p:
325
smiley_path, smiley_url = _smiley_loc[q]
326
smiley_path = os.path.abspath(smiley_path)
329
##print os.path.abspath(smiley_path)
332
## 'python': 'http://www.python.org',
333
## 'firedrop2': 'http://zephyrfalcon.org/labs',
334
## 'Pythonutils Mailing List': 'http://groups.google.com/group/pythonutils/',
335
## 'Jesus Fellowship Church': 'http://www.jesus.org.uk',
336
## 'Hans Nowak': 'http://zephyrfalcon.org/weblog2',
337
## 'rest': 'http://docutils.sourceforge.net',
338
## 'The Techie Blog': '/python/weblog/',
339
## 'The Voidspace Blogspot': '/voidspace/index.shtml',
344
##def standardlinks():
346
## for entry in _links:
348
## out.append(('.. _%s: ' % entry) + _links[entry])
349
## return '\n'.join(out) + '\n'
354
Add a globaldict with some values for the current page - e.g. the encoding being used and the current page location.
358
Added a set of standard acronyms.
361
Added the coloring advanced macro.
364
curlyl and curlyr added.
365
Some docstrings added.
366
Removed __all__ as it's not actually used.
367
Changed the smiley macro so that it doesn't create a new smiley object each run through.
368
colorize raises an import error if you attempt to use it and colorize.py isn't available.
369
Added escape option to the include macro.
370
In the event of error - colorize raises the error rather than trapping it.
371
Added the col=colorize alias.
372
Added the inc=include alias.
375
Integrated with rest2web, via the config file.