aboutsummaryrefslogtreecommitdiffstats
path: root/who.tl
blob: 794645c4e99a04b746a7c6d013fcfcdd6302e9bb (plain)
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
;; Copyright (c) 2003-2009, Dr. Edmund Weitz. All rights reserved.
;; Copyright (c) 2023, Kaz Kylheku. All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;;   * Redistributions of source code must retain the above copyright
;;     notice, this list of conditions and the following disclaimer.
;;
;;   * Redistributions in binary form must reproduce the above
;;     copyright notice, this list of conditions and the following
;;     disclaimer in the documentation and/or other materials
;;     provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

(in-package :tl-who-priv)

;; Returns the current HTML mode. :sgml for (SGML-HTML, :xml for
;; XHTML and :html5 for HTML5 (HTML syntax).
(defun html-mode ()
  *html-mode*)

;; Sets the output mode to XHTML or (SGML-)HTML.  mode can be
;; :sgml for (SGML-)HTML, :xml for XHTML or :html5 for HTML5 (HTML syntax).
(defun set-html-mode (mode)
  (ecaseq mode
    ((:sgml)
     (set *html-mode* :sgml
          *empty-attribute-syntax* t
          *empty-tag-end* ">"
          *prologue* "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"))
    ((:xml)
     (set *html-mode* :xml
          *empty-attribute-syntax* nil
          *empty-tag-end* " />"
          *prologue* "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"))
    ((:html5)
     (set *html-mode* :html5
          *empty-attribute-syntax* t
          *empty-tag-end* ">"
          *prologue* "<!DOCTYPE html>"))))

(defset html-mode set-html-mode)

;; Returns a string list corresponding to the `HTML' (in CL-WHO
;; syntax) in sexp.  Uses the function convert-tag-to-string-list
;; internally.  Utility function used by tree-to-template.
(defun process-tag (sexp body-fn)
  (let ((head (if (consp sexp) (first sexp) sexp))
        tag attr-list body)
    (cond
      ((keywordp sexp)
       (set tag sexp))
      ((atom head)
       (set tag head)
       ;; collect attribute/value pairs into attr-list and tag body (if
       ;; any) into body
       (let (attr)
         (for ((rest (rest sexp))) (rest) ((set rest (cddr rest)))
           (cond
             ((keywordp (first rest))
               (push (cons (first rest) (second rest)) attr))
             (t
               (set body rest
                    rest nil))))
         (set attr-list (nreverse attr))))
      ((listp head)
       (set tag (first head))
       (let (attr)
         (for ((rest (rest head))) (rest) ((set rest (cddr rest)))
           (if (keywordp (first rest))
             (push (cons (first rest) (second rest)) attr)))
       (set body (rest sexp)))))
    ;; tag macro expansion
    (flet ((finish ()
             (convert-tag-to-string-list tag attr-list body body-fn))
           (alist-to-plist (al)
             (mappend (tb ((a . b)) (list a b)) al))
           (process-elem (elem)
             (match-case elem
               (@(or @(keywordp)
                     (@(keywordp) . @nil)
                     ((@(keywordp) . @nil) . @nil))
                 [process-tag elem body-fn])
               (@else (compile-error sexp "produced non-tag form ~s"
                                     else)))))
      (iflet ((fn [*tag-macro* tag]))
        ;; macro found
        (let* ((attr-plist (alist-to-plist attr-list))
               (new-tag-elem [fn body . attr-plist]))
          (match-case new-tag-elem
            ;; returned keyword form
            ((progn . @stuff)
             (append-each ((elem stuff))
               (process-elem elem)))
            (@else (process-elem else))))
        ;; no macro: convert to string list
        (finish)))))

(defun attr-warning-macrolet (form)
  (with-gensyms (warn)
    ^(macrolet ((,warn (f . rest)
                   ^(compile-warning ,f
                                     "not recommended in attribute expr")))
       (macrolet ((fmt (. args)
                    ^(usr:fmt ,*args))
                  (escj (thing)
                    ^[(tojson (tostringp ,thing)) 1..-1])
                  ,*(collect-each ((sym '(htm noesc-fmt esc escq str)))
                      ^(,sym (:form f . rest) (,warn f) f)))
         ,form))))

;; Helper function for convert-tag-to-string-list which converts the
;; alist attr-list of attributes into a list of strings and/or Lisp
;; forms.
(defun convert-attributes (attr-list)
  (with-gensyms (=var=)
    (let ((aqc *attribute-quote-char*))
      (keep-matches (^(,orig-attr . ,val) attr-list)
        (let ((attr (maybe-upcase orig-attr))
              noesc)
          (when-match (noesc . @rest) val
            (set noesc t)
            (set val ^(progn ,*rest)))
          (if (constantp val)
            ;; Handle constant attribute value at macro time
            (let ((eval (eval val)))
              (cond
                ((null eval))
                ((eq eval t)
                 (if *empty-attribute-syntax*
                   ` @attr`
                   ` @attr=@aqc@attr@aqc`))
                ((or noesc *cl-who-compat*) ;; no escaping in CL-WHO compat mode
                  ` @attr=@aqc@(tostringp eval)@aqc`)
                (t ` @attr=@aqc@(html-encode (tostringp eval))@aqc`)))
            ;; For non-constant, do the same things as above but at runtime
            ^(let ((,=var= ,(attr-warning-macrolet val)))
               (cond
                 ((null ,=var=))
                 ((eq ,=var= t)
                  (str ,(if *empty-attribute-syntax*
                          ^` @,attr`
                          ^` @,attr=@,aqc@,attr@,aqc`)))
                 (t
                   ,(if (or noesc *cl-who-compat*)
                      ^(str ` @,attr=@,aqc@{,=var=}@,aqc`)
                      ^(str ` @,attr=@,aqc@(html-encode ,=var=)@,aqc`)))))))))))

;; Used by process-tag to convert `HTML' into a list
;; of strings.  tag is a keyword symbol naming the outer tag, attr-list
;; is an alist of its attributes (the car is the attribute's name as a
;; ;; keyword, the cdr is its value), body is the tag's body, and body-fn is
;; a function which should be applied to body.  The function must return
;; a list of strings or Lisp forms.
;; This is an ordinary function in TXR Lisp.
;; In CL-WHO, this is a generic function where the idea is that
;; you can use EQL specializers on the first argument to create
;; custom handling for different tags.
(defun convert-tag-to-string-list (tag-kw attr-list body body-fn)
  (let ((tag (maybe-upcase tag-kw))
        (body-indent
          ;; increase *indent* by 2 for body -- or disable it
          (when (and *indent* (not (member tag-kw *html-no-indent-tags*)))
            (ssucc *indent*))))
    (nconc
      (if *indent*
        ;; indent by *indent* spaces
        (list +newline+ (n-spaces *indent*)))
      ;; tag name
      (list "<" tag)
      ;; attributes
      (convert-attributes attr-list)
      ;; body
      (if body
        (append
          (list ">")
          ;; now hand over the tag's body to tree-to-template
          (let ((*indent* body-indent))
            [body-fn body])
          (when body-indent
            ;; indentation
            (list +newline+ (n-spaces *indent*)))
          ;; closing tag
          (list "</" tag ">"))
        ;; no body, so no closing tag unless defined in *html-empty-tags*
        (if (or (not *html-empty-tag-aware-p*)
                (member tag-kw *html-empty-tags*))
          (list *empty-tag-end*)
          (list ">" "</" tag ">"))))))

;; Transforms an HTML tree into an intermediate format - mainly a
;; flattened list of strings. Utility function used by tree-to-commands.
(defun tree-to-template (tree)
  (build
    (each ((element tree))
      (match-case element
        (@(or @(keywordp)
              (@(keywordp) . @nil)
              ((@(keywordp) . @nil) . @nil))
          ;; the syntax for a tag - process it
         (ncon [process-tag element tree-to-template]))
        ((noesc @(constantp @item))
         ;; (noesc ...) syntax on constant
         (add item))
        ((noesc . @nil)
         (compile-error tree "noesc requires single constant argument"))
        (@(consp)
         ;; list - insert as sexp
         (add ^(expander-let ((*indent* , *indent*)) ,element)))
        (@(stringp)
         ;; string - insert escaped version
         (add (html-encode* element)))
        ;; something else - insert verbatim
        (@else (add else))))))

(defun tree-to-commands (:key tree stream -- prologue (indent *indent*))
  (let ((*indent* indent))
    (when (and *indent*
               (not (integerp *indent*)))
      (set *indent* 0))
    (let ((in-string-p t)
          collector
          string-collector
          (template (tree-to-template tree)))
      (when prologue
        (push +newline+ template)
        (when (eq prologue t)
          (set prologue *prologue*))
        (push prologue template))
      (flet ((emit-string-collector ()
               ;; Generate a put-string form for what is currently
               ;; in string-collector.
               (list 'put-string
                     (cat-str (nreverse string-collector))
                     stream)))
        (each ((element template))
          (cond ((and in-string-p (stringp element))
                 ;; this element is a string and the last one
                 ;; also was (or this is the first element) -
                 ;; collect into string-collector
                 (push element string-collector))
                ((stringp element)
                 ;; the last one wasn't a string so we start
                 ;; with an empty string-collector
                 (set string-collector (list element)
                      in-string-p t))
                (string-collector
                 ;; not a string but string-collector isn't
                 ;; empty so we have to emit the collected
                 ;; strings first
                 (push (emit-string-collector) collector)
                 (set in-string-p nil
                      string-collector '())
                 (push element collector))
                (t
                 ;; not a string and empty string-collector
                 (push element collector))))
        (if string-collector
          ;; finally empty string-collector if
          ;; there's something in it
          (nreverse (cons (emit-string-collector)
                          collector))
          (nreverse collector))))))

;; Transform the enclosed body consisting of HTML as s-expressions
;; into Lisp code to write the corresponding HTML as strings to var -
;; which should either hold a stream or which'll be bound to stream if
;; supplied.
(defmacro with-html-output ((:key var : stream -- prologue indent . rest)
                            :form *cur-form* :env *cur-env*
                            . body)
  ^(let ((,var ,(or stream var)))
     (macrolet ((htm (. body)
                  ^(with-html-output (,',var nil :prologue nil)
                     ,*body))
                (noesc-fmt (. args)
                  ^(format ,',var ,*args))
                (fmt (. args)
                  (if *cl-who-compat*
                    ^(noesc-fmt ,*args)
                    ^(put-string (html-encode* (usr:fmt ,*args)) ,',var)))
                (esc (thing)
                  (with-gensyms (result)
                    ^(whenlet ((,result ,thing))
                       (put-string (html-encode* (tostringp ,result)) ,',var))))
                (escq (thing)
                  (with-gensyms (result)
                    ^(whenlet ((,result ,thing))
                       (put-string (html-encode (tostringp ,result)) ,',var))))
                (escj (thing)
                  (with-gensyms (result)
                    ^(whenlet ((,result ,thing))
                       (put-string [(tojson (tostringp ,result)) 1..-1] ,',var))))
                (str (thing)
                  (with-gensyms (result)
                    ^(whenlet ((,result ,thing))
                       (pprint ,result ,',var)))))
       ,*[apply tree-to-commands body var rest])))

(defmacro with-html-output-to-string ((:key var : string-form
                                            -- prologue indent)
                                      . body)
  ^(with-output-to-string (,var ,string-form)
     (with-html-output (,var nil :prologue ,prologue :indent ,indent)
       ,*body)))

(defun scrub-kw-args (key-params args)
  (let* ((kwp (find-package "keyword"))
         (keys [mapcar (op intern
                           (symbol-name
                             (tree-case @1
                               ((prop t) prop)
                               (prop prop)))
                           kwp)
                       key-params]))
    (build
      (for ((iter args)) (iter) ((set iter (cddr iter)))
        (tree-bind (prop val . t) iter
          (unless (memq prop keys)
            (add prop val)))))))

(defmacro deftag (:form f keyword attr-param-list body-pattern . body)
  (unless (keywordp keyword)
    (compile-error f "~s argument must be a keyword" keyword))
  (let ((rest-param (if (consp attr-param-list)
                      (last attr-param-list 0)
                      attr-param-list))
        (key-params (if (consp attr-param-list)
                      (butlast attr-param-list 0))))
    (with-gensyms (body-arg)
      ^(progn
         (set [*tag-macro* ,keyword]
              (lambda (:key ,body-arg -- ,*attr-param-list)
                (mac-env-param-bind *cur-form* *cur-env* ,body-pattern ,body-arg
                  ,*(if (and rest-param key-params)
                      ^((set ,rest-param
                             (scrub-kw-args ',key-params ,rest-param))))
                  ,*body)))
         ,keyword))))