~openerp-community/openobject-server/training

« back to all changes in this revision

Viewing changes to presentation.en/tools/lib/macros.py

  • Committer: Fabien Pinckaers
  • Date: 2009-08-04 16:14:19 UTC
  • Revision ID: fp@tinyerp.com-20090804161419-vwan9tdtjheeua87
add

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# macros.py
 
2
 
 
3
# Subversion Details
 
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 $
 
8
 
 
9
# macros for rest2web
 
10
# http://www.voidspace.org.uk/python/rest2web
 
11
 
 
12
# Adapted from macros.py for Firedrop2 by Hans Nowak
 
13
# http://zephyrfalcon.org
 
14
 
 
15
# Copyright Michael Foord, 2004 & 2005.
 
16
# Released subject to the BSD License
 
17
# Please see http://www.voidspace.org.uk/python/license.shtml
 
18
 
 
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
 
25
 
 
26
# FIXME: Sort smiley stuff....
 
27
# XXXX
 
28
smiley_path, smiley_url = 'smilies', '/smilies/'
 
29
 
 
30
 
 
31
adblock = '    <!--#include virtual="/includes/adblock.shtml" -->'
 
32
hiddennetwork = '    <!--#include virtual="/includes/_hiddennetwork.shtml" -->'
 
33
 
 
34
import cStringIO
 
35
import os
 
36
import sys
 
37
import traceback
 
38
 
 
39
uservalues = {}
 
40
namespace = {}
 
41
 
 
42
def _set_uservalues(n, u):
 
43
    """Set the namespace and uservalues for the page."""
 
44
    global namespace
 
45
    global uservalues
 
46
    uservalues = u
 
47
    namespace = n
 
48
 
 
49
##sys.__stdout__.write(os.getcwd())
 
50
 
 
51
# curlyl and curlyr is a way of including literal
 
52
# curly brackets in pages
 
53
curlyl = '{'
 
54
curlyr = '}'
 
55
 
 
56
cl = curlyl
 
57
cr = curlyr
 
58
 
 
59
# {emoticon;name}  e.g. {emoticon;smile}
 
60
def emoticon(name):
 
61
    """
 
62
    Return a link to a named gif file
 
63
    in the emoticons/ folder.
 
64
    """
 
65
    name = name.strip()
 
66
    if q in ('movpy', 'firedrop2'):
 
67
        return '<img src="emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
 
68
    else:
 
69
        return '<img src="/emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
 
70
emo = emoticon
 
71
 
 
72
def acronym(acronym, meaning=None):
 
73
    """
 
74
    Return the HTML for an acronym.
 
75
    """
 
76
    if meaning is None:
 
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)
 
80
acro = acronym
 
81
 
 
82
# a dictionary of standard acronyms
 
83
# keys should be lowercase
 
84
acronyms = {
 
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',
 
114
    }
 
115
 
 
116
def include(filename, escape='False'):
 
117
    """
 
118
    Include a file in the page.
 
119
    HTML only of course.
 
120
    """
 
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('  ', '&nbsp;&nbsp;')
 
127
    return data
 
128
inc = include
 
129
 
 
130
try:
 
131
    import smiley as smiley_module
 
132
except ImportError:
 
133
    def smiley(text):
 
134
        """
 
135
        Attempting to use this without having the smiley module available
 
136
        will raise an ImportError.
 
137
        """
 
138
        raise ImportError, "Importing smiley.py failed."
 
139
#
 
140
else:
 
141
    smile = None
 
142
    def smiley(text):
 
143
        """
 
144
        Create a smiley.
 
145
        The smiley lib is only created on the first run through.
 
146
        """
 
147
        global smile
 
148
        if smile is None:
 
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
 
153
sm = smiley
 
154
 
 
155
 
 
156
# syntax coloring with Pygments
 
157
try:
 
158
    from pygments import highlight
 
159
    from pygments.lexers import get_lexer_by_name
 
160
    from pygments.formatters import HtmlFormatter
 
161
except ImportError:
 
162
    def colorize(filename):
 
163
        raise ImportError, 'Importing pygments failed.'
 
164
    class coloring:
 
165
        def open(self, data):
 
166
            raise ImportError, 'Importing pygments failed.'
 
167
        def close(self, *args):
 
168
            pass
 
169
else:
 
170
    class coloring:
 
171
 
 
172
        lexer_options = dict(
 
173
                stripall=True
 
174
        )
 
175
        formatter_options = dict(
 
176
            linenos=True,
 
177
            cssclass="highlight"
 
178
        )
 
179
 
 
180
        def __init__(self, lexer_options=None, formatter_options=None):
 
181
            self.lexer_options = self.lexer_options.copy()
 
182
            if lexer_options:
 
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)
 
187
 
 
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)
 
192
 
 
193
        def close(self, *args):
 
194
            pass
 
195
 
 
196
    def colorize(filename):
 
197
        """Format Python script as syntax coloured HTML.
 
198
 
 
199
        Using the appropriate css it will be nicely colored.
 
200
 
 
201
        Needs the Pygments package.
 
202
 
 
203
        """
 
204
        fullname = os.path.join(filename)
 
205
        f = open(fullname, 'r')
 
206
        data = f.read()
 
207
        f.close()
 
208
        #
 
209
        colorizer = coloring()
 
210
        return colorizer.open(data)
 
211
 
 
212
col = colorize
 
213
 
 
214
 
 
215
def name(n):
 
216
    return '<a name="%s" id="%s"></a>' % (n, n)
 
217
 
 
218
def title(text, size=3):
 
219
    """For titles of a named size"""
 
220
    return '<h%s>%s</h%s>' % (size, text, size)
 
221
 
 
222
def small(text):
 
223
    return '<small>%s</small>' % text
 
224
 
 
225
#############################################################
 
226
#
 
227
# Anything below this line is specific to Voidspace
 
228
# and probably not useful (except maybe as examples....)
 
229
 
 
230
def target_title(target, title, cls='', ):
 
231
    """Return a title as a target."""
 
232
    t = '<a href="#%s" %s><h2>%s</h2></a>'
 
233
    if cls:
 
234
        cls = 'class="%s"' % cls
 
235
    return t % (target, cls, title)
 
236
 
 
237
def index_title(Title, subtitle=''):
 
238
    """target_title for voidspace"""
 
239
    a = target_title('index', Title, 'titlelink')
 
240
    if subtitle:
 
241
        a += title(subtitle)
 
242
    return a
 
243
 
 
244
class IndexTable:
 
245
    """
 
246
    For generating Index Tables
 
247
 
 
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.
 
253
    """
 
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(' ')
 
257
        cols = int(cols)
 
258
        start = ('<div class="index-table"><table class="index-table"'
 
259
            'border="1" width="%s" summary="%s">')
 
260
        start = start % (width, data.pop(0))
 
261
        #
 
262
        out = [start, '<colgroup>']
 
263
        width = 100 / cols
 
264
        for i in range(cols):
 
265
            out.append('<col width="%s" />' % width)
 
266
        out.append('</colgroup>')
 
267
        #
 
268
        title = data.pop(0)
 
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">')
 
272
        #
 
273
        out.append('<tr>')
 
274
        i = -1
 
275
        while i < len(data) -1:
 
276
            i += 1
 
277
            val = data[i].split(' ', 1)
 
278
            if len(val) == 2:
 
279
                target, name = val
 
280
            else:
 
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>&nbsp;</td>')
 
288
        out.append('</tr><tr>')
 
289
        for i in range(cols):
 
290
            out.append('<td>&nbsp;</td>')
 
291
        out.append('</tr></tbody></table></div>')
 
292
        return '\n'.join(out)
 
293
 
 
294
    def close(self, *args):
 
295
        pass
 
296
 
 
297
 
 
298
_link = "/cgi-bin/voidspace/downman.py?file=%s"
 
299
def dl(file, text=''):
 
300
    """Create a download link for downman."""
 
301
    if not text:
 
302
        text = file
 
303
    link = _link % file
 
304
    return '<a href="%s">%s</a>' % (link, text)
 
305
 
 
306
 
 
307
# a dictionary allowing you to dynamically
 
308
# assign your smiley URL depending on where you're running this
 
309
# from.
 
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/'),
 
318
                }
 
319
 
 
320
p = os.getcwd().replace('/', '\\')
 
321
q = True
 
322
while p and q:
 
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)
 
327
        break
 
328
 
 
329
##print os.path.abspath(smiley_path)
 
330
 
 
331
##_links = {
 
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',
 
340
##    '': '',
 
341
##    '': '',
 
342
##}
 
343
##
 
344
##def standardlinks():
 
345
##    out = ['']
 
346
##    for entry in _links:
 
347
##        if entry:
 
348
##            out.append(('.. _%s: ' % entry) + _links[entry])
 
349
##    return '\n'.join(out) + '\n'
 
350
 
 
351
"""
 
352
TODO
 
353
 
 
354
Add a globaldict with some values for the current page - e.g. the encoding being used and the current page location.
 
355
 
 
356
CHANGELOG
 
357
2005/06/16
 
358
Added a set of standard acronyms.
 
359
 
 
360
2005/06/03
 
361
Added the coloring advanced macro.
 
362
 
 
363
2005/05/31
 
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.
 
373
 
 
374
2005/05/28
 
375
Integrated with rest2web, via the config file.
 
376
 
 
377
"""
 
378