File: sample.em

package info (click to toggle)
empy 4.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 808 kB
  • sloc: python: 7,673; sh: 22; makefile: 6
file content (445 lines) | stat: -rw-r--r-- 16,955 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env nothing -- This is a bangpath, it will be commented out.
@# Bangpaths are handled properly (the above line will not appear).
#! This line, however, will appear (not the first line in the file).
@# This is a comment.  This should not appear in the processed output.
@* This is an inline comment.  It continues until the ending delimiter. *@
@* This is also an inline comment.
Note that it can span multiple lines. *@
@*** The number of asterisks that start an inline comment determine
how many starts it takes to end it.  One asterisk * or two asterisks **
can appear inside this inline comment. ***@
This is text.  It should appear in the processed output. 
This is a literal at sign: @@.
This is a line continuation; @
this will appear on the same line.
Note that it will actually eat any white@ space (one word).
@{
# The em.py script has to be somewhere in sys.path!
import em
}@
@# Note the @{ ... }@ convention to suppress the newline following the }.
@# Also note that comments are completely tossed: This is not evaluated: @(x).

@# Escape codes; this requires at least Python 2.4.
This will appear on one line.@\nThis will appear on a separate line.
This is separated by a tab:@\tSee?
These are uppercase As (presuming an ASCII-compatible encoding): @
A, @\q1001, @\o101, @\d065, @\x41, @\u0041, @\U00000041.
Literals: @\(@\)@\[@\]@\{@\}@\<@\>@\\.

@# Literal markup.
Literal markup: @`This will not be evaluated at all: 1 + 1 = @(1 + 1)`.
Multiple backquotes: @```To evaluate 1 + 1 you'd write @`(1 + 1)````.
Multiline backquotes: @``Lorem ipsum @
dolor sit amet, @
consectetur adipiscing elit.``

@# The basics.
@{
import sys, math
x = 4
s = 'alpha'
word = "book"
l = [3, 2, 1]
def square(n):
    return n**2
friends = ['Albert', 'Betty', 'Charles', 'Donald']
class Container:

    def __init__(self, value):
        self.value = value

    def square(self):
        return square(self.value)
c = Container(3)
}@
The basics: The square of @(x) is @(x**2), or @(square(x)).
Internal whitespace is fine: @( x ) squared is @( square(x) ).
Statements: @{sys.stdout.write("%d**2 = %d" % (x, square(x)))}.
Whitespace too: @{ sys.stdout.write("%d**2 = %d (still)" % (x, square(x))) }.
@{
print("But only on single-line statement expansions.")
if 1:
    print("Internal whitespace on multi-line statements is significant.")
for i in range(2):
    print("Normal Python indentation rules must be followed here.")
}@
Simple expressions: x is @x, l is @l, s is "@s," and @x squared is @square(x).
Literals too: x is @x, but would be written @@x.
Trailing dots are ignored: The value of x is @x.
Quotes outside of expansions are also ignored: This is quoted: "x is @x."
@# Whitespace is important in simple expressions.
Array subscription: The first element of l is @l[0].
But this is not: The first element of l is not @l [0].
That was equivalent to: @(l) and then [0], not @l[0].
But whitespace can go inside the brackets: @l[0] is @l[ 0 ].
Same with functions: @square(x) is @square( x ).
The same applies to the other forms.
Involved: The contained value is @c.value.
More involved: The square of the contained value is @c.square().
Following expressions: Pluralize "@word" as "@(word)s," or maybe "@word@ s."
By default str is used (@s), but you can use repr if you want (@repr(s)).
Conditional expressions: @(x ? "x is true" ! "x is false").
Pluralization: How many words? @x word@(x != 1 ? 's').
Protected expressions: @(foo $ "foo is not defined").
Also here, whitespace isn't important: @(bar$"bar isn't defined either").
The math module has @(math ? "been imported" $ "not been imported").
The re module has @(re ? "been imported" $ "not been imported").
Division by zero is @(x/0 $ "illegal").
To swallow errors, use None: @(buh $ None) [two spaces].
This is self-expanding: @$2 + 2$(this will get replaced with 4)$
You can expand multiple times: @
@empy.expand("@empy.expand('@$2 + 2$hugalugahglughalug$')")
Is asdf defined?  @(empy.defined('asdf') ? 'Yes' ! 'No')
@{
asdf = 123
}@
Just defined it.  Is it defined now?  @(empy.defined('asdf') ? 'Yes' ! 'No')
@# Use of the functional expressions.
@{
def show(*args):
    sys.stdout.write(' '.join(['[%s]' % x for x in args]))
class Curry:
    def __init__(self, function, *first):
        self.function = function
        self.first = first

    def __call__(self, *rest):
        return self.function(*(self.first + rest))
}@
This will appear in @show{brackets}.
This will appear in @show{brackets @{empy.write("also")}}.
This will appear in @show{more}{brackets}.
This will appear in @Curry(show, "even"){more}{brackets}.
Here are repeated braces: @show{{braces}}.
Here are nested braces: @show{@\{braces@\}}.
Here are stray braces; @show{starting @\{} and @show{ending @\}}.

@# More complex examples, including classes.
@{
class C:
    def __init__(self, name):
        self.name = name

    def greetString(self):
        return "Hello, %s" % self.name

    def printGreeting(self):
        sys.stdout.write("Hello, %s" % self.name) # implicit None return

c = C("empy")
}@
c's class is @c.__class__.__name__.
c's name is @c.name.
Method call: @c.greetString().
Note that None is not expanded: @(None) [two spaces].
But the string 'None' is, of course, printed fine: @('None').
So a function can return None for side effects only: @c.printGreeting().

@# Control.
@{
a = 5 # something positive
b = -3 # something negative
z = 0 # zero
}@
If: a is @[if a > 0]positive@[end if].
If/else: b is @[if b > 0]positive@[else]negative@[end if].
If/elif/else: cmp(a, b) is @
@[if a < b]negative@[elif a > b]positive@[else]zero@[end if].
If/elif/elif/else: z equals @[if z == a]a@[elif z == b]b@[elif z == z]z@[else]none of the above@[end if].
Testing parsing: @[if 2 in [1, 2, 3]]checks out@[end if].
Some integers:@
@[for i in range(10)] @i@[end for].
The same integers (testing parsing):@
@[for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] @i@[end for].
Those integers which are even:@
@[for i in range(10)]@[if i % 2 == 1]@[continue]@[end if] @i@[end for].
Those integers less than 5:@
@[for i in range(10)]@[if i >= 5]@[break]@[end if] @i@[end for].
For/else:@[for i in range(3)] @i@[else] also works@[end for].
Countdown:@
@{j = 10}@[while j >= 0] @j@{j -= 1}@[end while].
Even countdown:@
@{j = 10}@[while j >= 0]@[if j % 2 == 1]@{j -= 1}@[continue]@[end if] @j@{j -= 1}@[end while].
Interrupted countdown:@
@{j = 10}@[while j >= 0]@[if j <= 5]@[break]@[end if] @j@{j -= 1}@[end while].
While/else: @[while z]shouldn't get here@[else]works@[end while].
Tuple unpacking:@[for x in [1, 2, 3, 4]] <@x>@[end for].
Tuple unpacking:@[for x, in [[1], [2], [3], [4]]] <@x>@[end for].
Tuple unpacking:@[for (x,) in [[1], [2], [3], [4]]] <@x>@[end for].
Tuple unpacking:@[for x, y in [[1, 2], [3, 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for (x), (y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for (x, y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for x, (y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for x, (y,) in [[1, [2]], [3, [4]]]] <@x, @y>@[end for].
Tuple unpacking:@[for (x), y in [[1, 2], [3, 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for (x,), y in [[[1], 2], [[3], 4]]] <@x, @y>@[end for].
Tuple unpacking:@[for (x,), (y,) in [[[1], [2]], [[3], [4]]]] <@x, @y>@[end for].
More tuple unpacking:@[for (((x))), ((y),) in [[1, [2]], [3, [4]]]] <@x, @y>@[end for].
Garbage is @[try]@hglhagulahguha@[except NameError]not defined@[end try].
Named with comma: Garbage is @[try]@hglhagulahguha@[except NameError, e]not defined: @e.__class__.__name__@[end try].
Named with tuple and comma: Garbage is @[try]@hglhagulahguha@[except (NameError, AttributeError), e]not defined: @e.__class__.__name__@[end try].
Named with as: Garbage is @[try]@hglhagulahguha@[except NameError as e]not defined: @e.__class__.__name__@[end try].
Named with tuple and as: Garbage is @[try]@hglhagulahguha@[except (NameError, AttributeError) as e]not defined: @e.__class__.__name__@[end try].
Division by zero is @[try]@(a/z)@[except ZeroDivisionError]illegal@[end try].
Catch all: @[try]@ghlaghlhagl@[except]something happened@[end try].
Else works: @[try]@[except]oops@[else]else@[end try].
Else with finally works with no exception: @
@[try]@[except]@[else]else@[finally], with finally@[end try].
Finally works with no exception: @[try]@[finally]finally@[end try].
Finally works with exception: @
@[try]@[try]@(1/0)@[finally]finally@[end try]@[except], and caught@[end try].
Break can escape out of a try:@
@[for x in range(10)]@[try] @x@[if x == 5] and break!@[break]won't show@[end if]@[except]Oops!@[end try]@[end for]
So can a continue:@
@[for x in range(10)]@[try]@[if x % 2 == 1]@[continue]@[end if] @x@[except Exception as e]Oops: @e@[end try]@[end for] (evens).
@[def sign(x)]@x is @[if x > 0]positive@[elif x < 0]negative@[else]zero@[end if]@[end def]@
Define: @sign(a), @sign(b), @sign(z).
Defined: a is @[defined a]defined@[else]undefined@[end defined]; @
q is @[defined q]defined@[else]undefined@[end defined].
@{
class Manager:

    def __init__(self):
        pass

    def employ(self):
        sys.stdout.write(" employed,")

    def __enter__(self):
        sys.stdout.write(" entered,")
        return self

    def __exit__(self, *exc):
        sys.stdout.write(" exited,")
}@
With: expression and variable:@[with Manager() as m]@m.employ()@[end with] and done.
With: existing variable:@[with m]@m.employ()@[end with] and done.
With: expression only:@[with Manager()] (not employed,)@[end with] and done.

@# Diversions.  Again, a trailing @ is used to suppress the following newline.
A. This text is undiverted.
@empy.startDiversion(1)@
C. This text is diverted.
@empy.stopDiverting()@
B. This text is also undiverted.
@empy.playDiversion(1)@
D. Again, this text is undiverted.
@empy.startDiversion('a')@
E. This text is diverted and then undiverted@
@empy.stopDiverting()@
@empy.replayDiversion('a').
@empy.playDiversion('a') (this should appear twice).
@empy.startDiversion('q')@
F. This text is diverted and then cancelled.
@empy.playDiversion('q')@
G. This text is again undiverted.
@empy.startDiversion('x')@
X. This text will be purged and should not appear!
@empy.stopDiverting()@
H. There should be one remaining diversion: @empy.getAllDiversionNames().
@empy.dropDiversion('x')@
I. But not after dropping it: @empy.getAllDiversionNames().
@{
# Finally, make a manual diversion and manipulate it.
empy.createDiversion('z')
zDiversion = empy.retrieveDiversion('z')
zDiversion.write("J. This should be the final diversion, created manually.\n")
empy.playDiversion('z')
}@

@# Parsing checks.
Blanks: @(''), @(""), @(''''''), @("""""").
Single quotes: @('\''), @("'"), @("""'""").
Double quotes: @("\""), @('"'), @('''"''').
Triple quotes: @("\"\"\""), @('"""'), @('\'\'\''), @("'''").
Quotes surrounded by spaces: @(""" " """), @(''' ' ''').
At signs: @('@'), @("@"), @('''@'''), @("""@""").
Close parentheses: @(')'), @(")"), @( (")") ), @( (')') ).
Close parentheses in quotes: @("')'"), @('\')\'').
Close braces with an intervening space: @
@{sys.stdout.write("}")} @{sys.stdout.write('}')}.
Repr of a backquote: @repr('`').
Exes: @("?"?'x'), @(0?"!"!'x'), @("]"?'x'), @(1?"x"!"]").
Dollar signs: @("$"$None), @(hugalug?"$"$"$"), @(1?hugalug$"$").
These are strings:
@'single quoted string'
@"double quoted string"
@'single quoted string with escaped \'single quotes\''
@"double quoted string with escaped \"double quotes\""
@'''triple single quoted string'''
@"""triple double quoted string"""
@'single quoted string with "double quotes"'
@"double quoted string with 'single quotes'"
@'''triple single quoted continued \
string'''
@"""triple double quoted continued \
string"""
@'''triple single quoted
...multi-line string'''
@"""triple double quoted
... multi-line string"""

@# Significators.
@%a
@%b 
@%c "x"
@%d "x" 
@%e "x y"
@%f "x y" 
Encountered significators:
a and b should be None: @repr(__a__), @repr(__b__)
c and d should be 'x': @repr(__c__), @repr(__d__)
e and f should be 'x y': @repr(__e__), @repr(__f__)

@# Filters.
@{
import emlib
}@
This line should be in mixed case.
@empy.setFilter(emlib.FunctionFilter(lambda x: x.lower()))@
This line should be all lowercase.
@empy.setFilter(emlib.FunctionFilter(lambda x: x.upper()))@
This line should be all uppercase (how gauche).
@empy.setFilterChain([emlib.LineDelimitedFilter(),
                      emlib.FunctionFilter(lambda x: '[%s]\n' % x[:-1])])@
This line should be bracketed.
So should this line.
@empy.setFilterChain([emlib.SizeBufferedFilter(5),
                      emlib.FunctionFilter(lambda x: '*' + x)])@
There should be stars every five characters on this line.
@empy.setFilter(emlib.FunctionFilter(lambda x: ''))@
This line should not appear at all!
@empy.resetFilter()@
This line should be back to mixed case.
@empy.resetFilter()@
@empy.appendFilter(emlib.FunctionFilter(lambda x: x.upper()))@
This line should be all uppercase again.
@empy.resetFilter()@
@empy.prependFilter(emlib.FunctionFilter(lambda x: x.lower()))@
This line should be all lowercase again.
@empy.resetFilter()@
@empy.appendFilter(emlib.FunctionFilter(lambda x: x.upper()))@
@empy.appendFilter(emlib.LineDelimitedFilter())@
@empy.appendFilter(emlib.FunctionFilter(lambda x: '[%s]\n' % x[:-1]))@
This line should be all uppercase with brackets.
@empy.resetFilter()@
@empy.appendFilter(emlib.FunctionFilter(lambda x: x.upper()))@
@empy.prependFilter(emlib.FunctionFilter(lambda x: x.lower()))@
This line should be all uppercase (lowercase has been filtered).
@empy.resetFilter()@
@empy.prependFilter(emlib.FunctionFilter(lambda x: x.upper()))@
@empy.appendFilter(emlib.FunctionFilter(lambda x: x.lower()))@
This line should be all lowercase (uppercase has been filtered).
@empy.resetFilter()@
This line should be back to mixed case (again).

@# Contexts, metaoperations.
@{
class FakeFile:

    def __init__(self, line):
        self.line = line

    def read(self, bufferSize=None):
        result = self.line
        self.line = ''
        return result

    def readline(self):
        result = self.line
        self.line = ''
        return result

    def close(self): pass

fakeFile = FakeFile("2 + 2 = @(2 + 2) [@empy.getContext()].\n")
}@
The original context is @empy.getContext().
File inclusion [@empy.getContext()]: @empy.include(fakeFile)@
Expansion [@empy.getContext()]: @
@empy.expand("This should be appear [@empy.getContext()]") @
on the same line as this [@empy.getContext()].
More expansion [@empy.getContext()]:
@{sys.stdout.write(empy.expand("Another expansion [@empy.getContext()]"))}.
This is the next line [@empy.getContext()].
Quoting: @empy.quote("x when quoted would be '@x' or @x").
More quoting: @empy.quote("This will be @doubled but '''@this is not'''").
And here's the original context again: @empy.getContext().
@{
saved = empy.getContext().save()
}@
Setting the context name:
@?OtherName
Name should now be 'OtherName': @empy.getContext()
Setting the context line number:
@!1000
Line number should now be 1001: @empy.getContext()
Restoring context: @
@empy.setContextData(name=saved.name, line=saved.line + 10)@empy.getContext().
Creating a new context ...
@empy.pushContext(empy.newContext())@
The new context is: @empy.getContext().
@?NewName
The context name is now 'NewName': @empy.getContext().
@!1000
The line number is now 1000 (new context does not advance): @empy.getContext().
@empy.popContext()@
Back to the old context: @empy.getContext().

@# Embedded interpreters and standalone expansion.
@{
q = 1
}@
Interpreter's q is @q.
@{
interp = None
try:
    interp = em.Interpreter()
    interp.string("@{q = 10}")
    interp.string("Embedded interpreter's q is @q.\n")
finally:
    if interp:
        interp.shutdown()
}@
Interpreter's q is still @q; the embedded interpreter had no effect.
Standalone expansion: @em.expand("1 + 1 is @(1 + 1).")
With locals: @em.expand("@x + @y is @(x + y).", locals={'x': 2, 'y': 3})
@{
g = {}
}@
With globals g: @em.expand("@{x = 10}g's x is @x.", globals=g)
Still with globals: @em.expand("g's x + 1 is @(x + 1).", globals=g)
g's x is still @g['x'].

@# Hooks.
@{
class SampleHook(emlib.Hook):
    def test(self):
        self.interp.write('[SampleHook.test invoked]')

sampleHook = SampleHook()
empy.addHook(sampleHook)
}@
Invoking the sample hook: @empy.invokeHook('test').
@{
empy.removeHook(sampleHook)
}@

@# Custom.
@{
def customCallback(contents, empy=empy):
    empy.write('<%s>' % contents)
empy.registerCallback(customCallback)
}@
Using a custom markup: @<This appears in angle brackets>.
You can use multiple angle brackets: @<<This also appears in angle brackets>>.
It can contain angle brackets: @<<This contains angle brackets inside <>!>>.
It can also span multiple lines: @<<<This spans
multiple
lines.>>>

@# Finalizers.
@empy.atExit(lambda: empy.write("This is the last line.\n"))@
@empy.atExit(lambda: empy.write("This is the penultimate line.\n"))@
This is the third to last line.