CL-HTTP Appendix D: HTML Macro Reference


Reference Manual | Prev: Appendix C. Export Type Reference


This appendix documents all major HTML generation macros and functions provided by the CL-HTTP HTML facility. These operators generate valid HTML markup when executed within a response function, writing to a stream (typically the HTTP output stream). Each operator belongs to a versioned package corresponding to the HTML standard it implements.

CL-HTTP provides four HTML generation packages, each superseding its predecessor with additional operators and arguments:

Application code should use the operators from the most recent package appropriate for the target browsers. The HTML5 package inherits all operators from earlier packages, so (in-package :html5) gives access to the full set. Operators are listed below under their introducing package; later packages often extend the same operator with additional keyword arguments. The active HTML generation version is controlled by html:*dtd-version*.

Common Keyword Arguments

Most HTML 4.0 and HTML5 operators accept a standard set of keyword arguments in addition to their element-specific parameters. These are omitted from the per-operator tables below for brevity:

HTML5 operators additionally accept global attributes: :hidden, :content-editable, :draggable, :spell-check, :role, :data-attributes.

Document Structure

These operators establish the overall structure of an HTML document: the document wrapper, the preamble (HEAD), and the body (BODY).

OperatorSinceTypeKey ArgumentsDescription
with-html-document HTML2 Macro :stream, :declare-dtd-version-p, :language, :direction Wraps the entire HTML document in <html>...</html>. In HTML 4.0, :declare-dtd-version-p can be :transitional, :frameset, :strict, or nil. In HTML5, emits <!DOCTYPE html> when non-nil. XHTML adds :character-encoding and :xml-declaration.
with-document-preamble HTML2 Macro :stream, :profile, :language, :direction Wraps the HEAD section. :profile (HTML 4.0) is a URI or list of URIs for metadata profiles. Body forms emit preamble declarations (title, links, styles, meta).
with-document-body HTML2 Macro :stream, :class, :id, :style, :events
Deprecated: :background-url, :background, :foreground, :link, :visited-link, :active-link
Wraps the BODY section. In HTML 4.0+, color arguments are deprecated in favor of style sheets. Events include :load and :unload.
with-standard-document-body HTML4.0 Macro :color-scheme, :stream Like with-document-body but applies the standard color scheme from *standard-color-scheme*. Deprecated.
declare-title HTML2 Function title, :language, :direction, :stream Declares the document title within the preamble. title is a string or a function of (stream). Every document must declare exactly one title.
declare-base-reference HTML2 Function reference, :target, :stream Declares the BASE URI for resolving relative URIs. reference must be an absolute URI (URL object or string). :target sets the default frame target. Note: modern browsers compute the base automatically; use sparingly.
declare-link HTML2 Function :reference, :relation, :inverse, :media-type, :media, :target, :link-language, :charset, :stream Declares a LINK element in the preamble. :relation specifies the link type (e.g., "stylesheet"). :media (HTML 4.0) can be :screen, :print, :handheld, :tty, :tv, :projection, :braile, :aural, or :all.
declare-meta-info HTML2 Function value, :name, :header, :scheme, :language, :direction, :stream Declares META information. :name or :header specifies the type; value is the content.
with-document-style-declared HTML4.0 Macro media-type, :media, :title, :language, :direction, :stream Wraps a STYLE element in the preamble. media-type is the MIME type (e.g., (:text :css)). Body forms write style sheet content to the stream.

Block Elements

Block-level elements structure page content into headings, paragraphs, divisions, and other block-level containers.

OperatorSinceTypeKey ArgumentsDescription
with-section-heading HTML2 Macro (heading :level :stream)
Deprecated: :alignment
Wraps a section heading (H1–H6). heading is a string or function. :level defaults to *section-level*, automatically incremented by nesting. The deprecated :alignment argument is superseded by CSS.
with-paragraph HTML2 Macro :stream, :fresh-line
Deprecated: :alignment
Wraps a P element. :alignment (deprecated) accepts :left, :center, :right, :justify. Use CSS instead.
with-division HTML4.0 Macro :inline-p, :stream Wraps a DIV element (or SPAN when :inline-p is true). Used for grouping content for styling or scripting.
with-centering HTML4.0 Macro :stream Wraps a CENTER element. Deprecated; use CSS text-align: center instead.
with-text-block-style HTML4.0 Macro (block-style :cite :stream) Wraps text in a block-level style. block-style can be :quotation (BLOCKQUOTE), :address (ADDRESS), :citation (CITE), or :code (CODE). :cite is a URI for the source (quotation only).
with-paragraph-style HTML4.0 Macro (paragraph-style :cite :alignment :stream) Like with-text-block-style but with additional :alignment (deprecated). Prefer with-text-block-style.
with-verbatim-text HTML2 Macro :stream, :fresh-line
Deprecated: :width
Wraps a PRE element. Text is rendered in a fixed-width font exactly as written, preserving whitespace.
horizontal-line HTML2 Function :stream, :fresh-line
Deprecated: :size, :width, :alignment, :shade
Writes an HR element. In HTML 4.0+, visual attributes are deprecated; use CSS for styling. :size is line thickness in pixels; :width is line length (integer for pixels, float 0–1 for percentage).
break-line HTML2 Function :stream
Deprecated: :clear
Writes a BR element. :clear (deprecated) controls clearing around floated images: :left, :right, :all.
with-editing-change HTML4.0 Macro (change-type :universal-time :reason :stream) Marks inserted or deleted text. change-type is :insertion (INS) or :deletion (DEL). :universal-time is a Lisp universal time; :reason is a URI citing the change rationale.
with-language-direction HTML4.0 Macro :language, :direction, :stream Wraps a BDO element to override text directionality.

Inline Markup

Inline operators apply styling and semantic markup to text spans within block elements.

OperatorSinceTypeKey ArgumentsDescription
with-rendition HTML2 Macro (rendition :stream) Renders text according to rendition, which can be: :bold (B), :italic (I), :large (BIG), :small (SMALL), :strike (S, deprecated), :subscript (SUB), :superscript (SUP), :teletype (TT), :underline (U, deprecated), :code (CODE), :keyboard (KBD), :sample (SAMP), :variable (VAR), :citation (CITE), :definition (DFN), :abbreviation (ABBR).
with-emphasis HTML4.0 Macro (emphasis :cite :stream) Renders text with semantic emphasis. emphasis can be: :emphasis (EM), :strong (STRONG), :quotation (BLOCKQUOTE), :quote (Q), :definition (DFN), :citation (CITE), :keyboard (KBD), :variable (VAR), :code (CODE), :sample (SAMP), :abbreviation (ABBR), :acronym (ACRONYM). :cite is available for :quotation and :quote.
with-font HTML4.0 Macro :size, :relative-size-p, :color, :stream Wraps a FONT element. Deprecated. :size is 1–7 (absolute, default 3) or a relative offset when :relative-size-p is non-nil. Use CSS font properties instead.

Lists

List operators generate ordered, unordered, and definition lists. Items are emitted within the list environment using enumerating-item.

OperatorSinceTypeKey ArgumentsDescription
with-enumeration HTML2 Macro (stream enumeration-style :compact :type :start :reversed) Establishes a list environment. enumeration-style can be: :itemize (UL), :enumerate (OL), :definition (DL), :directory (deprecated), :menu (deprecated). :type (deprecated) overrides the bullet style: for :enumerate — :capital-letters, :small-letters, :large-roman, :small-roman, :arabic; for :itemize — :solid-disc, :circle, :square. :start sets the initial counter value. HTML5 adds :reversed for descending OL numbering. You must use the enumerating-item from the same package for reliable results.
enumerating-item HTML2 Macro (stream :head :icon-url :type) Emits a list item within with-enumeration. For :definition style, :head provides the term (DT); the body provides the definition (DD). :head can be a string, list of strings, or function. :icon-url prepends an image to the item. :type (deprecated) overrides the bullet for this item.

Tables

Table operators generate HTML tables with rows, cells, captions, row groups, and column groups.

OperatorSinceTypeKey ArgumentsDescription
with-table HTML3.2 Macro :width, :cell-spacing, :cell-padding, :border, :frame, :rules, :summary, :stream
Deprecated: :alignment, :background
Establishes a TABLE environment. :width is a float (0–1 for percentage) or integer (pixels). :cell-spacing (default 2) controls space between cells. :cell-padding (default 1) controls space between cell content and walls. :border is an integer for frame width. :frame controls which sides are visible: :void, :above, :below, :hsides, :vsides, :lhs, :rhs, :box, :border. :rules controls internal grid lines: :none, :groups, :rows, :cols, :all. :summary describes the table for non-visual rendering.
with-table-row HTML3.2 Macro :horizontal-alignment, :vertical-alignment, :stream
Deprecated: :background
Wraps a TR element. :horizontal-alignment can be :left, :center, :right, :justify, or :char. :vertical-alignment can be :top, :middle, :bottom, or :baseline.
with-table-cell HTML3.2 Macro :header-p, :horizontal-alignment, :vertical-alignment, :column-span, :row-span, :abbreviation, :axis, :scope, :headers, :stream
Deprecated: :height, :width, :background, :break-lines-p
Wraps a TD or TH element. :header-p selects TH (header cell) vs. TD (data cell). :column-span and :row-span control cell spanning. :scope can be :row, :col, :rowgroup, :colgroup. :abbreviation provides a short description for non-visual user agents.
with-caption HTML3.2 Macro :stream
Deprecated: :alignment
Wraps a CAPTION element within a table.
with-table-row-group HTML4.0 Macro (group-type :horizontal-alignment :vertical-alignment :stream) Wraps a THEAD, TBODY, or TFOOT element. group-type is :head, :body, or :foot.
with-table-column-group HTML4.0 Macro :span, :width, :horizontal-alignment, :vertical-alignment, :stream Wraps a COLGROUP element. :span specifies the number of columns in the group.

Links and Media

These operators create hyperlinks, inline images, and other embedded content.

OperatorSinceTypeKey ArgumentsDescription
with-anchor-noted HTML2 Macro :reference, :local-reference, :tag, :relation, :inverse, :target, :media-type, :link-language, :charset, :tab-index, :access-key, :shape, :coordinates, :stream Wraps body forms in an A element. :reference is a URL (object or string). :local-reference is a fragment identifier. :tag (deprecated in XHTML; use :id) creates a named anchor. :target designates the frame: :blank, :self, :parent, :top, or a frame name string. :shape can be :rectangle, :circle, or :polygon with :coordinates for image map areas.
note-anchor HTML2 Function text, :reference, :local-reference, :target, :stream, and same as with-anchor-noted Convenience function: writes text (string or function) wrapped in an A element. For computed anchor content, use with-anchor-noted instead.
image HTML2 Function image-url, alternative-text, :width, :height, :accept-coordinates-at-url, :client-side-image-map, :border, :description, :name, :stream
Deprecated: :alignment, :vertical-space, :horizontal-space
Writes an IMG element. image-url is the image source; alternative-text is the alt text (required). :accept-coordinates-at-url can be a URL (server-side image map), t (coordinates to search URL), or :no-url. :width and :height are in pixels; providing them allows browsers to lay out the page before images load. :description provides a longer description supplementing the alt text.
with-object HTML4.0 Macro :name, :code, :data, :code-type, :data-type, :width, :height, :resources, :base, :standby, :stream Wraps an OBJECT element for generic embedded content (images, applets, multimedia). Supersedes APPLET.
with-java-applet HTML4.0 Macro (code width height :alignment :code-base :stream) Wraps an APPLET element (deprecated). Use with-object instead.
with-client-image-map HTML4.0 Macro (name :stream) Wraps a MAP element for client-side image maps.

Forms

Form operators generate HTML forms for user input. The accept-input generic function dispatches on input type objects to generate specific form controls.

OperatorSinceTypeKey ArgumentsDescription
with-fillout-form HTML2 Macro (action destination :encoding-type, :name, :target, :accept-media-types, :accept-charsets, :stream) Establishes a FORM environment. action is :post, :get (deprecated), :mail, or :none. destination is the target URI. :encoding-type defaults to '(:multipart :form-data). :target specifies the frame: :blank, :self, :parent, :top, or a frame name. Forms must not be nested.
accept-input HTML2 Generic Function (input-type query-name &key :default :stream ...) The primary interface for generating form controls. input-type is a symbol naming the input type; query-name is the form field name. Additional keyword arguments depend on the input type. See the Input Types table below.
with-form-button HTML4.0 Macro (type :name, :value, :disabled, :stream)
HTML5 adds: :form-action, :form-method, :form-encoding-type, :form-no-validate, :form-target, :auto-focus, :form-id
Wraps a BUTTON element. type is :button, :submit, or :reset. Body forms can emit rich content (text and images) within the button. Use this when accept-input buttons are insufficient.
with-form-field-set HTML4.0 Macro :access-key, :stream
HTML5 adds: :disabled, :form-id, :name
Wraps a FIELDSET element to group related form controls.
with-form-field-legend HTML4.0 Macro :access-key, :alignment, :stream Wraps a LEGEND element within a fieldset, providing a caption for the grouped controls.
with-form-control-label HTML4.0 Macro :control-id, :access-key, :stream Wraps a LABEL element. :control-id associates the label with a form control by its ID.

Input Types for accept-input

The first argument to accept-input is a symbol naming the input type. Some types have nickname symbols shown in parentheses. All types accept :default, :disabled, :id, :class, :style, :events, :tab-index, and :access-key in addition to type-specific arguments.

Standard Input Types (HTML 2.0 through HTML 4.0)

Input TypeSinceHTML ElementType-Specific ArgumentsDescription
string (string+) HTML2 <input type="text"> :size, :max-length Single-line text input. Default size 72, max 240.
password HTML2 <input type="password"> :size, :max-length Password field with masked input. Default size 10.
multi-line-text HTML2 <textarea> :rows, :columns, :default
HTML5 adds: :placeholder, :required, :auto-focus, :max-length, :min-length, :wrap
Multi-line text area. Default 5 rows by 72 columns. :default can be a string or function. HTML5 :wrap is :hard or :soft.
hidden HTML2 <input type="hidden"> :default (required) Hidden field not displayed to the user. :default is required and can be an atom or a list (emits multiple hidden fields).
radio-button HTML2 <input type="radio"> :choices, :default, :layout, :enumeration, :preamble Radio button group. :choices is a list of atoms or (label :value value ...) plists. :layout can be :enumeration (with list wrapper), :none (inline), :division, or :inline.
checkbox HTML2 <input type="checkbox"> :choices, :default (list), :layout, :enumeration, :preamble Checkbox group. Like radio-button but allows multiple selections. :default is a list of selected values.
select-choices HTML2 <select> :choices, :default, :size, :sequence-p
HTML5 adds: :required, :auto-focus
Selection menu. :choices is a list of atoms, (label :value value) plists, or nested lists for option groups. :sequence-p enables multiple selection. :size of :pull-down-menu gives a dropdown.
submit-button HTML2 <input type="submit"> :label, :image-url, :alternative-text
HTML5 adds: :form-action, :form-method, :form-encoding-type, :form-no-validate, :form-target
Form submission button. :label sets the button text (default "Submit"). HTML5 form-* arguments override the enclosing form's attributes for this button.
reset-button HTML2 <input type="reset"> :label, :image-url, :alternative-text Form reset button. :label sets the button text (default "Reset").
client-side-button HTML4.0 <input type="button"> :label, :image-url, :alternative-text
HTML5 adds: :form-action, :form-method, :form-encoding-type, :form-no-validate, :form-target, :auto-focus
Client-side push button, typically used with script event handlers.
file HTML4.0 <input type="file"> :size, :max-length File upload control. Requires the enclosing form to use (:multipart :form-data) encoding.
image HTML4.0 <input type="image"> :image-url, :alternative-text, :accept-coordinates-at-url Graphical submit button using an image.

HTML5 Input Types

HTML5 adds specialized input types with built-in browser validation and tailored user interfaces (e.g., date pickers, sliders, color choosers). All HTML5 types additionally accept :placeholder, :required, :auto-focus, :auto-complete, and :list where applicable.

Input TypeNicknameHTML ElementType-Specific ArgumentsDescription
email-field email <input type="email"> :size, :max-length, :multiple, :placeholder, :required, :pattern Email address input. :multiple allows comma-separated addresses.
url-field url-input <input type="url"> :size, :max-length, :placeholder, :required, :pattern Absolute URL input with browser validation.
number-field number-input <input type="number"> :min, :max, :step, :placeholder, :required Numeric input with spinner control.
range-field range <input type="range"> :min, :max, :step, :list Imprecise numeric value via slider control.
date-field date-input <input type="date"> :min, :max, :step, :required Date picker (year, month, day; no time zone).
datetime-local-field datetime-local <input type="datetime-local"> :min, :max, :step, :required Local date and time picker (no time zone).
month-field month <input type="month"> :min, :max, :step, :required Month and year picker.
week-field week <input type="week"> :min, :max, :step, :required Week-year and week number picker.
time-field time-input <input type="time"> :min, :max, :step, :required Time of day picker (no time zone).
color-field color-input <input type="color"> :auto-complete, :list Color picker (#rrggbb format).
search-field search <input type="search"> :size, :max-length, :placeholder, :required, :pattern Search term input. Semantically indicates search purpose; functionally equivalent to text.
telephone-field tel <input type="tel"> :size, :max-length, :placeholder, :required, :pattern Telephone number input. No syntax enforcement; mobile devices present a numeric keypad.

Scripts and Foreign Language Code

Design Rationale

Web applications frequently embed client-side code written in JavaScript or other scripting languages within HTML documents generated by Lisp. CL-HTTP's script infrastructure provides a clean abstraction barrier between Lisp and foreign language code, with several benefits:

Script Operators

OperatorSinceTypeKey ArgumentsDescription
with-script HTML4.0 Macro (media-type :script-location, :hide-javascript, :no-content, :charset, :stream)
HTML5 adds: :async
Wraps a SCRIPT element. media-type is a MIME type such as (:text :javascript). Body forms emit the script source. :script-location loads a script from a URI instead. :no-content adds defer. Use with-script for anonymous inline scripts. For named, reusable scripts, prefer define-script. Deprecated: :language.
without-script-capability HTML4.0 Macro :stream Wraps a NOSCRIPT element. Body forms provide alternate HTML for browsers not executing scripts.
define-script HTML4.0 Macro (name (language) :documentation, :location, :displays-content, :charset, :caller, :script) Registers a named script in the specified scripting language. See Defining and Using Scripts below.
declare-script NS2.0, HTML4.0 Generic function (script stream &optional force-write-p) Emits a script declaration in the document preamble. If the script has a URL, references it; otherwise writes the script body inline. force-write-p forces inline output even when a URL exists. Use for scripts that take no arguments.
write-script NS2.0, HTML4.0 Generic function (script stream &rest lambda-list) Writes the script body to the stream, passing additional arguments to the script's writer function. Use for scripts whose output depends on runtime parameters (URLs, configuration values, session state).
intern-script HTML4.0 Function (name language &key url if-does-not-exist) Looks up or creates a named script object. :if-does-not-exist is :error (default), :soft (returns NIL), or :create.

Defining and Using Scripts

define-script registers a named script with optional writer and caller functions. It takes two forms for the :script and :caller arguments:

Constant string form — the script body is a literal string, written verbatim with write-string. This example from the Genera Document Examiner defines bookmark management functions that use the browser's localStorage API:

(html:define-script dex-bookmarks (java-script)
  :documentation "Document Examiner bookmark management (localStorage)."
  :script "
function dexAddBookmark() {
  var topic = document.getElementById('dex-current-topic');
  if (!topic) return;
  var name = topic.getAttribute('data-topic');
  if (!name) return;
  var bookmarks = JSON.parse(localStorage.getItem('dex-bookmarks') || '[]');
  if (!bookmarks.some(function(b) { return b.topic === name; })) {
    bookmarks.unshift({topic: name, time: Date.now()});
    localStorage.setItem('dex-bookmarks', JSON.stringify(bookmarks));
  }
  dexRenderBookmarks();
  dexShowPane('bookmarks');
}
")

The entire JavaScript function is a Lisp string constant. No Lisp values are interpolated — the script is self-contained. This is appropriate when the script operates entirely on client-side state (DOM elements, localStorage, sessionStorage).

Writer function form — the script body is computed by a Lisp function that can interpolate server-side values. This example from the SSE log window creates an EventSource connection to a server-supplied URL:

(html:define-script log-window-statistics-sse (java-script)
  :documentation "EventSource client for SSE statistics updates."
  :script ((script stream events-url frameset-url)
           script
           (fast-format stream "var source = new EventSource('~A');~%"
                        events-url)
           (write-string
            "source.addEventListener('statistics', function(e) {
  document.getElementById('statistics').innerHTML = e.data;
});" stream)
           (write-string "source.onerror = function() {" stream)
           (fast-format stream "  window.top.location = '~A';"
                        frameset-url)
           (write-string "};" stream)))

The writer function receives the script object as its first argument, the output stream as its second, and any additional arguments passed by write-script. Here events-url and frameset-url are server-side URL strings computed at request time, while the JavaScript event handling code is written as string constants.

Using scripts in pages: Constant scripts are emitted with declare-script; parameterized scripts with write-script. Both go in the document preamble. This example from the Genera Document Examiner declares three constant scripts and writes one parameterized init script:

(html:with-document-preamble (:stream stream)
  ;; ... title, CSS ...
  ;; Constant scripts — no arguments, emitted verbatim:
  (html:declare-script
    (html:intern-script "DEX-BOOKMARKS" :java-script) stream t)
  (html:declare-script
    (html:intern-script "DEX-HISTORY" :java-script) stream t)
  (html:declare-script
    (html:intern-script "DEX-PANE-SWITCHING" :java-script) stream t)
  ;; Parameterized script — topic and query from the request:
  (html:write-script
    (html:intern-script "DEX-PAGE-INIT" :java-script)
    stream topic query))

And this example from the SSE log window writes a parameterized script that creates an EventSource connection to a server-supplied URL:

(html:with-document-preamble (:stream stream)
  ;; ... title, CSS ...
  (html:write-script
    (html:intern-script "LOG-WINDOW-STATISTICS-SSE" :java-script)
    stream
    *log-window-statistics-events-url*
    *log-window-url*))

Note: define-script converts the symbol name to an uppercase string. Use the same uppercase string when calling intern-script to look up the script.

See examples/genera-doc.lisp and examples/log-window.lisp for complete working examples.

Events and Event Handlers

Most HTML elements accept an :events argument that binds intrinsic event handlers to client-side script code. Events are specified as a list of handler specifications, each of the form:

((event-keyword . language-keyword) command)

where event-keyword is one of the CL-HTTP event names, language-keyword is a scripting language (typically :java-script), and command is a string containing the handler code.

Basic example — a clickable button that calls a JavaScript function:

(html:with-division (:inline-p t
                     :class "button"
                     :title "Save the document"
                     :events '(((:mouse-click . :java-script)
                                "saveDocument()"))
                     :stream stream)
  (write-string "Save" stream))

This emits: <span class='button' title='Save the document' onclick='saveDocument()'>Save</span>

Multiple events — an element can bind several events at once:

(html:with-division (:inline-p t
                     :class "interactive"
                     :events '(((:mouse-over . :java-script)
                                "highlight(this)")
                               ((:mouse-out . :java-script)
                                "unhighlight(this)")
                               ((:mouse-click . :java-script)
                                "selectItem(this)"))
                     :stream stream)
  (write-string "Hover or click me" stream))

From the Genera Document Examiner — pane-switching buttons use :mouse-click events to call JavaScript functions defined via define-script:

;; "Add Bookmark" button calls dexAddBookmark() from dex-bookmarks script
(html:with-division
  (:inline-p t :class "dex-btn"
   :title "Add the current topic to your bookmarks"
   :events '(((:mouse-click . :java-script) "dexAddBookmark()"))
   :stream stream)
  (write-string "Add Bookmark" stream))

;; "Bookmarks" pane-switching button
(html:with-division
  (:inline-p t :id "dex-btn-bookmarks" :class "dex-btn"
   :title "Show saved bookmarks"
   :events '(((:mouse-click . :java-script)
              "dexShowPane(\"bookmarks\")"))
   :stream stream)
  (write-string "Bookmarks" stream))

Note how the event handler strings reference JavaScript functions that were defined via define-script and emitted in the document preamble. This keeps the Lisp code concerned only with the binding between HTML elements and named script functions, not with the JavaScript implementation.

The following table maps CL-HTTP event keywords to HTML event attributes:

CL-HTTP KeywordHTML AttributeTriggered When
:mouse-clickonclickElement is clicked
:mouse-double-clickondblclickElement is double-clicked
:mouse-downonmousedownMouse button pressed
:mouse-uponmouseupMouse button released
:mouse-overonmouseoverMouse enters element
:mouse-outonmouseoutMouse leaves element
:mouse-moveonmousemoveMouse moves within element
:key-downonkeydownKey pressed
:key-pressonkeypressKey pressed and released
:key-uponkeyupKey released
:input-focusonfocusElement receives focus
:input-defocusonblurElement loses focus
:new-valueonchangeForm control value changes
:selectonselectText is selected in a field
:submitonsubmitForm is submitted
:resetonresetForm is reset
:loadonloadDocument or image finishes loading
:unloadonunloadDocument is unloaded

The event handler table is defined in *event-handlers* (server/html4.lisp) and can be extended with additional scripting languages or events.

HTML5 Semantic Elements

HTML5 introduces semantic elements that convey structural meaning beyond generic DIV/SPAN containers. All accept the standard HTML5 arguments (:id, :class, :style, :language, :direction, :events, :stream) plus HTML5-specific global attributes (:hidden, :content-editable, :draggable, :spell-check, :role, :data-attributes).

OperatorTypeHTML ElementDescription
with-header Macro HEADER Introductory content or navigational aids. Typically contains headings, logos, or search forms.
with-footer Macro FOOTER Footer content for its nearest sectioning ancestor. Typically contains author info, copyright, or related links.
with-navigation Macro NAV Section of navigation links.
with-article Macro ARTICLE Self-contained composition: a blog post, news article, forum entry, or similar independent content.
with-section Macro SECTION Generic thematic grouping of content, typically with a heading.
with-aside Macro ASIDE Content tangentially related to surrounding content: sidebars, pull quotes, or annotations.
with-main-content Macro MAIN Dominant content of the document body. Only one MAIN element per document.
with-figure Macro FIGURE Self-contained content referenced from the main flow: illustrations, diagrams, code listings, photos.
with-figure-caption Macro FIGCAPTION Caption for a FIGURE element.
with-details Macro DETAILS Disclosure widget that can be toggled open/closed. :open sets the initial state.
with-summary Macro SUMMARY Visible heading for a DETAILS element.
with-dialog Macro DIALOG Dialog box or interactive component. :open controls initial visibility.
with-search Macro SEARCH Contains form controls or content related to search functionality.
with-menu Macro MENU Toolbar-style list of commands or interactive items.
with-address Macro ADDRESS Contact information for its nearest ARTICLE or BODY ancestor.
with-heading-group Macro HGROUP Groups a set of heading elements (H1–H6) as a single composite heading.

HTML5 Inline and Data Elements

OperatorTypeHTML ElementKey ArgumentsDescription
with-mark Macro MARK — Highlighted text for reference or relevance annotation.
with-time-element Macro TIME :datetime Machine-readable date/time. :datetime provides the ISO 8601 value.
with-data-element Macro DATA :value Associates machine-readable :value with human-readable body content.
with-ruby Macro RUBY — Ruby annotation container (East Asian typography).
with-ruby-text Macro RT — Ruby text component within a RUBY element.
with-ruby-parenthesis Macro RP — Fallback parenthesis for browsers that do not support ruby annotations.
with-bidirectional-isolation Macro BDI — Isolates a span of text for bidirectional formatting.
with-slot Macro SLOT :name Named slot placeholder for Web Components (shadow DOM).
with-template Macro TEMPLATE — HTML template fragment not rendered until instantiated by script.

HTML5 Multimedia and Interactive

OperatorTypeHTML ElementKey ArgumentsDescription
with-audio Macro AUDIO :src, :preload, :auto-play, :loop-p, :muted, :controls, :cross-origin, :plays-inline Embeds audio content. Body can contain SOURCE elements and fallback text.
with-video Macro VIDEO :src, :preload, :auto-play, :loop-p, :muted, :controls, :width, :height, :poster, :cross-origin, :plays-inline Embeds video content. :poster is a URL for the placeholder image.
with-picture Macro PICTURE — Container for multiple SOURCE elements providing responsive image variants.
with-canvas Macro CANVAS :width, :height Drawing surface for script-based graphics (2D context or WebGL).
with-meter Macro METER :value, :min, :max, :low, :high, :optimum Scalar measurement within a known range (e.g., disk usage, relevance score).
with-progress-bar Macro PROGRESS :value, :max Progress indicator for a task. Indeterminate when :value is omitted.
with-output-element Macro OUTPUT :for-ids, :name, :form-id Container for the result of a calculation or user action. :for-ids lists the IDs of contributing elements.
with-data-list Macro DATALIST — Contains OPTION elements providing predefined suggestions for an input control (referenced via the input's :list argument).

Frames (Deprecated)

Frame operators are deprecated in HTML5 but retained for backward compatibility with HTML 4.0 Frameset documents.

OperatorSinceTypeKey ArgumentsDescription
with-document-frameset HTML4.0 Macro :rows, :columns, :stream Wraps a FRAMESET element. Requires :declare-dtd-version-p :frameset in with-html-document.
without-frame-capability HTML4.0 Macro :stream Wraps a NOFRAMES element providing content for browsers that do not support frames.

Document Look Facility

The document look facility separates page chrome from page content. A look is a CLOS object; response functions generate their content through the look macros, and the look supplies the surrounding structure -- stylesheet declarations, headers, footers, signatures -- by specializing three generic functions. Code written against the look macros needs no change when a site installs, replaces, or personalizes its look. Under the default look the macros are exact pass-throughs to with-html-document, with-document-preamble, and with-document-body, so adopting them costs nothing.

Look Objects

NameTypeDescription
document-look Class The base class for looks. Carries a name and a property list.
document-look-default Class The default look: all three generation methods pass through, producing exactly the output of the direct HTML macros.
css-document-look Class Adds style-type and style-url slots for cascading style sheet support.
cl-http-look Class CL-HTTP's page style: declares the site stylesheet in the preamble, and wraps the body in header, body, and footer divisions with an optional heading, image, and header index, closing with the CL-HTTP signature. Bound as the value of *cl-http-document-look*.
create-document-look Macro Creates a look object: (create-document-look :class 'cl-http-look :style-url "/css/site.css"). Keyword arguments other than :class pass through as initargs.
*standard-document-look* Variable The ambient look consulted by all look macros when no explicit :document-look is supplied. Initially a document-look-default.

Installing a Look

Three mechanisms select the look, from widest to narrowest scope:

  1. Site-wide: set *standard-document-look* in the server configuration. Every page generated through the look macros -- including all Dynamic Forms pages (see Chapter 13.5) -- follows it with no further changes.
  2. Dynamic extent: (with-document-look (look) ...) binds *standard-document-look* within the body, for a subtree of pages or a single response.
  3. Per user: specialize the generic function user-document-look on a user class and pass (user-document-look http:*server*) as the :document-look argument, personalizing page appearance by authenticated user.

Generation Macros

OperatorSinceTypeKey ArgumentsDescription
with-document-look-html HTML4.0 Macro :document-look, :declare-dtd-version-p, :language, :direction, :stream The toplevel environment: binds the look with with-document-look and emits the document via write-document-html. Contains a with-document-look-preamble and a with-document-look-body.
with-document-look-preamble HTML4.0 Macro :document-look, :profile, :language, :direction, :stream Emits the document preamble via write-document-preamble. BODY provides the page-specific head declarations (title, base reference, per-page styles).
with-document-look-body HTML4.0 Macro :document-look, :class, :id, :title, :style, :events, :stream, look-specific keywords Emits the document body via write-document-body. Additional keywords pass through to the look's body method -- cl-http-look understands :heading, :heading-class, :image, :header-index, :header-class, :body-class, and :footer-class.
with-cl-http-html-document HTML4.0 Macro :declare-dtd-version-p, :stream Wraps a document in *cl-http-document-look* (falling back to *standard-document-look* when null): the standard CL-HTTP page with heading, horizontal rules, and signature footer.

The Specialization Protocol

A look customizes page generation by specializing three generic functions on its class. Each receives the look, a writer function that emits the page-specific content, the stream, and the keyword arguments collected by the corresponding macro:

Generic FunctionWrapsTypical Specialization
write-document-html with-html-document (the :around method) Rarely specialized; the :around method already emits the doctype and <html> element.
write-document-preamble with-document-preamble :before methods add head declarations ahead of the page's own -- cl-http-look declares the document style type and the stylesheet link here, so page-level style elements override it in the cascade.
write-document-body with-document-body (the :around method) Primary methods wrap the content writer in structure -- cl-http-look emits the header division (image, heading, header index), calls (call-next-method) inside the body division with *section-level* starting at 2, and closes with the footer division and signature.

The default primary methods simply call the writer, and the :around methods supply the enclosing HTML elements -- which is why the default look reproduces the direct macros exactly. Because cl-http-look's body method owns section level 1, page headings written inside the body render at level 2 when that look is installed.

HTML5 and HTML4 Document Looks

The facility is defined once in the HTML4.0 package and inherited; only the doctype chain is specialized in HTML5, because that is the only place the generated markup differs. html5:with-document-look-html, html5:write-document-html, and html5:with-cl-http-html-document (reached through the HTML nickname) produce <!DOCTYPE html> documents, while the html4.0: versions produce the HTML 4.01 DTD declaration. Look classes, installed looks, and preamble/body method specializations are shared: one look serves both document generations.

Look Example

;; A site look: stylesheet plus a standard footer.
(defclass acme-look (html:document-look)
  ((style-url :initarg :style-url :reader acme-style-url)))

(defmethod html:write-document-preamble :before ((look acme-look) writer stream &rest args)
  (declare (dynamic-extent args)
           (ignore writer args))
  (html:declare-link :reference (acme-style-url look) :relation "stylesheet"
                     :media-type "text/css" :stream stream))

(defmethod html:write-document-body ((look acme-look) writer stream &rest args)
  (declare (dynamic-extent args)
           (ignore writer))
  (multiple-value-prog1
      (call-next-method)
    (html:with-division (:class "footer" :stream stream)
      (html:horizontal-line :stream stream)
      (write-string "Copyright 2026, Acme." stream))))

;; Install it site-wide in the configuration:
(setq html:*standard-document-look*
      (html:create-document-look :class 'acme-look :style-url "/css/acme.css"))

;; Response functions just use the look macros:
(defun respond-to-acme-page (url stream)
  (http:with-successful-response (stream :html)
    (html:with-document-look-html (:stream stream)
      (html:with-document-look-preamble (:stream stream)
        (html:declare-title "Acme" :stream stream))
      (html:with-document-look-body (:stream stream)
        (html:with-section-heading ("Welcome" :stream stream)
          (html:with-paragraph (:stream stream)
            (write-string "Content, wrapped in the site look." stream)))))))

Usage Example

The following response function illustrates the typical pattern of HTML generation using the macro facility:

(defun respond-to-example (url stream)
  (http:with-successful-response (stream :html)
    (html:with-html-document (:declare-dtd-version-p :transitional :stream stream)
      (html:with-document-preamble (:stream stream)
        (html:declare-title "Example Page" :stream stream)
        (html:declare-link :reference "/style.css" :relation "stylesheet"
                           :media-type '(:text :css) :stream stream))
      (html:with-document-body (:stream stream)
        (html:with-section-heading ("Welcome" :stream stream)
          (html:with-paragraph (:stream stream)
            (write-string "This page was generated by " stream)
            (html:with-rendition (:bold :stream stream)
              (write-string "CL-HTTP" stream))
            (write-string "." stream)))
        (html:with-enumeration (stream :itemize)
          (html:enumerating-item (stream)
            (html:note-anchor "Home" :reference "/" :stream stream))
          (html:enumerating-item (stream)
            (html:note-anchor "About" :reference "/about" :stream stream)))
        (html:horizontal-line :stream stream)
        (html:with-paragraph (:stream stream)
          (html:image "/logo.png" "CL-HTTP Logo"
                      :width 200 :height 60 :stream stream))))))