]> gitweb.factorcode.org Git - factor.git/blob - contrib/embedded.factor
HTTPD tools moved to contrib/furnace and updated to use the new framework
[factor.git] / contrib / embedded.factor
1 IN: embedded
2 USING: sequences kernel parser math namespaces io ;
3
4 ! if example.fhtml contains:
5 ! <html>
6 !     <head><title>Simple Embedded Factor Example</title></head>
7 !     <body>
8 !       <% 5 [ %><p>I like repetition</p>
9 !       <% drop ] each %>
10 !     </body>
11 ! </html>
12 !
13 ! then "example.fhtml" run-embedded-file prints to stdout:
14 ! <html>
15 !     <head><title>Simple Embedded Factor Example</title></head>
16 !     <body>
17 !         <p>I like repetition</p>
18 !         <p>I like repetition</p>
19 !         <p>I like repetition</p>
20 !         <p>I like repetition</p>
21 !         <p>I like repetition</p>
22
23 !     </body>
24 ! </html>
25
26 : get-text ( string -- remainder chunk )
27     "<%" over start dup -1 = [
28             drop "" swap
29     ] [
30             2dup head >r tail r>
31     ] if ;
32
33 : get-embedded ( string -- string code-string )
34     ! regexps where art thou?
35     "%>" over 2 start* 2dup swap 2 -rot subseq >r 2 + tail r> ;
36
37 : get-first-chunk ( string -- string )
38     dup "<%" head? [
39             get-embedded parse %
40     ] [
41             get-text , \ write ,
42     ] if ;
43
44 : embedded>factor ( string -- )
45     dup length 0 > [
46             get-first-chunk embedded>factor
47     ] [ drop ] if ;
48
49 : parse-embedded ( string -- quot )
50     #! simple example: "numbers: <% 3 [ 1 + pprint ] each %>"
51     #! => "\"numbers: \" write 3 [ 1 + pprint ] each"
52     [ embedded>factor ] [ ] make ;
53
54 : eval-embedded ( string -- ) parse-embedded call ;
55
56 : with-embedded-file ( filename quot -- )
57     [
58         file-vocabs
59         over file set ! so that reload works properly
60         >r <file-reader> contents r> call
61     ] with-scope ;
62
63 : parse-embedded-file ( filename -- quot )
64     [ parse-embedded ] with-embedded-file ;
65
66 : run-embedded-file ( filename -- )
67     [ eval-embedded ] with-embedded-file ;
68
69 : embedded-convert ( infile outfile -- )
70     <file-writer> [ run-embedded-file ] with-stream ;
71
72 PROVIDE: contrib/embedded ;