% *** html_pl.tex *** (Version 96.1.1)
% A Simple HTML Package for Prolog and CLP systems - Documentation
% 
% Copyright (C) 1996 UPM-CLIP.
% 
% This package is free software; you can redistribute it and/or
% modify it under the terms of the GNU Library General Public
% License as published by the Free Software Foundation; either
% version 2 of the License, or (at your option) any later version.
% 
% This package is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% Library General Public License for more details.
% 
% You should have received a copy of the GNU Library General Public
% License along with this package; if not, write to the Free
% Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
% 
% M. Hermenegildo (herme@fi.upm.es) & D. Cabeza (dcabeza@fi.upm.es)
% using input from L. Naish's forms and F. Bueno's previous Chat interface

\documentclass[dvips,12pt]{article}
\usepackage[dvips]{graphics}
\usepackage{html}

\renewcommand{\topfraction}{.8}
\renewcommand{\bottomfraction}{.8}
\renewcommand{\textfraction}{.2}

\newcommand{\var}[1]{{\sl #1}}
\newcommand{\titem}[1]{\item[\latexfbox{\tt #1}]}
\newcommand{\latexfbox}[1]{\latex{\fbox{#1}}\html{{#1}}}
\newcommand{\linktosource}[2]{\htmladdnormallink{{\tt #1}}{source/#2#1}}

\begin{document}
\begin{latexonly}
\title{{\tt html.pl}:\\ A Simple HTML Package \\
for Prolog and CLP Systems\\
{\Large\em Description and User's Manual}\\
{\large (Version 96.1.1)}
}  
\end{latexonly}
\begin{htmlonly}
\title{html.pl: An HTML Package for (C)LP systems (V96.1.1)}
\end{htmlonly}

\author{D. Cabeza \and M.\ Hermenegildo
  \thanks{Computer Science Department, Technical University of Madrid
    (UPM), Spain, {\tt dcabeza@fi.upm.es, herme@fi.upm.es}.}}

\date{15 Mar 1996}
\maketitle

\begin{abstract}
  We describe a simple, public domain, HTML package for LP/CLP systems.
  The package allows generating HTML documents easily from LP/CLP
  systems, including HTML {\em forms}. It also provides facilities for
  parsing the input provided by HTML forms, as well as for creating
  standalone form handlers.  The purpose of this document is to serve as
  a user's manual as well as a short description of the capabilities of
  the package.  The package was originally developed for SICStus Prolog
  and the UPM \&-Prolog/CIAO systems, but has been adapted to a number
  of popular LP/CLP systems.

  The document is also a WWW/HTML primer, containing sufficient
  information for developing medium complexity WWW applications in
  Prolog and other LP and CLP languages.
\end{abstract}

\section{Introduction}
Prolog, and its constraint based extensions, are excellent tools for
developing knowledge-based applications. It is often useful to
interface such applications to one of the main on-line information
exchange forums, the World Wide Web (WWW). 
%%\cite{web}. 
This Prolog HTML package aims at providing a set of library procedures
which should be useful in this process. The package allows generating
documents in HTML format, the native format of WWW documents, easily
from Prolog, including HTML {\em forms}. It also provides facilities for
parsing the input provided by HTML forms (independently of whether they
have been produced by a Prolog program or not), and for producing
stand-alone form handlers.  The purpose of this document is to serve as
a user's manual as well as a short description of the capabilities of
the package. The package was originally developed for SICStus Prolog
\cite{sicstus} and the UPM \&-Prolog \cite{ngc-and-prolog} and CIAO
systems \cite{ciao-ppcp,ciao-ilps95}, but has also been adapted to other
popular LP/CLP systems (see the {\tt Makefile} for details). It should
be straightforward to adapt it to other Prolog and CLP systems.

If you find this package useful and develop an application with it,\linebreak
we would appreciate if you mention our work by citing the user's
manual and/or by putting a pointer to its location in our WWW pages%
\latex{\linebreak
({\tt http://www.clip.dia.fi.upm.es/miscdocs/html\_pl/html\_pl.html})}.

\section{Getting and Installing {\tt html.pl}}

The latest version of the Prolog HTML package is available via
anonymous ftp from the \htmladdnormallinkfoot{CLIP ftp
  server.}{ftp://clip.dia.fi.upm.es/pub/software} 
To install simply uncompress and untar the distribution in a convenient
directory. Then edit the options in {\tt Makefile} to suit your system. In
particular, copy the files in the {\tt images} directory to an accessible
directory in your server and change
\begin{quote}
{\tt ICONDIR=http://www.clip.dia.fi.upm.es/images/}
\end{quote}
to point to this directory (if you cannot do that, bear in mind that
these images will have to travel from Spain, Europe!). Also, if you will
be generating {\tt cgi-bin} executables (as explained \hyperref{in this
  node}{in section }{}{cgibin}, only available in some systems) change
\begin{quote}
{\tt CGIBINDIR=/usr/local/etc/httpd/cgi-bin/}
\end{quote}
to point to a {\tt cgi-bin}-type directory where you have write access.
Finally, change {\tt SYSTEM} to the Prolog system you will be using (if
your system is not listed, perhaps you can make a compatibility file
\verb+c_*.pl+ for it, providing the necessary support predicates. If you
do so, please \htmladdnormallink{send us the changes!}
{mailto:clip@dia.fi.upm.es}). Now, run ``{\tt make html.pl}''. If your
OS does not have ``make'', then manually produce {\tt html.pl} from {\tt
  html0.pl} and the appropriate {\tt c\_*.pl} compatibility file,
changing {\tt <ICONDIR>} and {\tt <CGIBINDIR>} in the code to the
correct values.

Versions of this manual in ``{\tt .dvi}'', ``{\tt .ps}'', and ``{\tt
  .html}'' formats are provided in the distribution in the {\tt doc}
directory.
\begin{latexonly}
  The latest version of this manual can be accessed on-line from
  \begin{quote}
    {\tt http://www.clip.dia.fi.upm.es/miscdocs/html\_pl/html\_pl.html}
  \end{quote}
\end{latexonly}

\section{Contents of the Distribution}

\begin{description}
\item [\linktosource{README}{},
       \linktosource{COPYING.LIB}{}]
       Read these files before using the package.
\item [\linktosource{CHANGES}{}] History of the changes between versions.
\item [\linktosource{Makefile}{}] Makefile for producing {\tt
    html.pl}. Must be edited to suit your system.
\item [{\tt c\_\var{system}.pl}] Compatibility file for system
  \var{system}.
\item [\linktosource{html0.pl}{}] Main source code from which {\tt
    html.pl} is made by {\tt make}.
\item [\linktosource{html.pl}{}] This is the
  main library file which should be loaded into the application. The
  default version in the distribution is for \&-Prolog/CIAO, change
  {\tt Makefile} options and run {\tt make} to make a version for your
  system.
\item [\linktosource{doc}{}] Directory containing the documentation. 
\begin{description}
  \item [\linktosource{html\_pl.tex}{doc/}] This manual, in \LaTeX\ format.
  \item [\linktosource{html\_pl.ps}{doc/}] This manual, in postscript format.
  \item [\linktosource{html\_pl/html\_pl.html}{doc/}] This manual, in
    html format.  Needs also the other files in this directory.
\end{description}
\item [\htmlref{{\tt examples}}{examples}] Directory
  containing examples.
\item [\linktosource{images}{}] Directory containing standard images
  used in the package. 
\end{description}

\section{Using the Package}

The package comprises three basic building blocks: 

\begin{itemize}
\item Facilities for generating HTML documents (including forms).
\item Facilities for parsing input from HTML forms.
\item Facilities for producing stand-alone form handlers.
\end{itemize}

The functionality and predicates of each of these blocks are described in
the following sections. 

\subsection{Predicates for Generating HTML Documents}

\begin{description}
  \titem{output\_html(\var{F})} Accepts in \var{F} an HTML term (or a
  list of HTML terms) and sends to the standard output the text which
  is the rendering of the term(s) in HTML format.

  \titem{html\_term(\var{F},\var{L},\var{T})} Accepts in \var{F} an HTML 
  term and produces in \var{L} a list of atoms which are the rendering of
  the term in HTML format. \var{T} is the tail of this list and is
  usually {\tt []}. Used by {\tt output\_html/2}.
\end{description}

An {\em HTML term} is a Prolog term in which certain atoms and
structures represent special functionality at the HTML level. It can be
recursively a list of HTML terms.  The following are legal HTML terms:

\begin{verbatim}
hello
[hello, world]
['This is an ', em('HTML'), ' term']
\end{verbatim}

{\tt html\_term/3} in general leaves atoms in HTML terms unchanged,
but translates structures into the corresponding format in HTML,
applying then {\tt html\_term/2} recursively to their arguments.
\label{simplecode}For example, given the following code:
{\small
\begin{verbatim}
:- ['/usr/local/lib/prolog/html.pl'].

main :- 
  tell('html_simple.html'),
  icon_address(clip,ClipLogo),
  output_html([
    start,
    title('Simple HTML document generated from Prolog'),
    image(ClipLogo), nl,
    heading(1,'Simple HTML document'),
    'This document was produced with the ',tt('html.pl'),' library.', \\,
    'It has facilities for:',
    itemize([
      [em('Generating'),' HTML documents (including forms).'],
      [em('Parsing'),' input from HTML forms.'],
      [em('Producing'),' stand-alone forms handlers.'],
      etc
      ]),
    --,
    address('clip@dia.fi.upm.es'),
    end
  ]),
  told.
\end{verbatim}
} Loading this code and calling {\tt main/0} produces the file
\linktosource{html\_simple.html}{examples/},
 the contents of which are:
{\small
\begin{verbatim}
<html><title>Simple HTML document generated from Prolog</title>
<img src="http://www.clip.dia.fi.upm.es/images/clip.gif">
<h1>Simple HTML document</h1>
This document was produced with the <tt>html.pl</tt> library.<br>
It has facilities for:<ul>
<li> <em>Generating</em> HTML documents (including forms).
<li> <em>Parsing</em> input from HTML forms.
<li> <em>Producing</em> stand-alone forms handlers.
<li> etc
</ul>
<hr>
<address>clip@dia.fi.upm.es</address></html>
\end{verbatim}
}

\begin{latexonly}
  Visualizing this file with a WWW browser produces output similar to
  figure \ref{browser} (the best thing is to try it out with your
  favorite browser).
\begin{figure}[!tb]
\fbox{\fbox{
  \begin{minipage}{0.95\textwidth}
    \includegraphics{clip.ps}\\[10pt]
    \huge
    {\bf Simple HTML document}\\[10pt]
    \large
    This document was produced with the {\tt html.pl} library.\\
    It has facilities for:
    \begin{itemize}
    \item {\em Generating} HTML documents (including forms).
    \item {\em Parsing} input from HTML forms.
    \item {\em Producing} stand-alone forms handlers.
    \item etc
    \end{itemize}
    \rule{\textwidth}{1pt}\\
    {\em clip@dia.f{i}.upm.es}
  \end{minipage}
}}
\caption{\label{browser} Possible visualization of {\tt html\_simple.html}}
\end{figure}
\end{latexonly}

As was shown with the previous example, HTML terms may contain logic
variables, provided they are instantiated before the term is translated
or output.  This allows creating documents piecemeal, backpatching of
references in documents, etc.

In the following sections we list the meaning of the various Prolog
structures that represent special functionality at the HTML level.  Any
atom not included here is assumed to be normal text and will be passed
through to the HTML document. These sections are included for reference,
but in any case %
\htmladdnormallink{the source file}{source/html.pl} is clear enough
(perhaps more than this description). You can also examine \hyperref%
{the example files.}%
{section }{ to see examples.}%
{examples}

\subsubsection{General Structures}
\label{genstruct}

Basically, HTML has two kinds of components: HTML {\em elements} and
HTML {\em environments}.  An HTML element has the form \mbox{{\tt
    <NAME \var{Attributes} >}} were {\tt NAME} is the name of the
element and \var{Attributes} is a (possibly empty) sequence of
attributes, each of them being either an attribute name or an attribute
assignment as \mbox{{\tt name="Value"}}.

An HTML environment has the form \mbox{{\tt <NAME \var{Attributes} >
  \var{Text}}} \verb+</NAME>+ were {\tt NAME} is the name of the
environment an \var{Attributes} has the same form as before.

The general Prolog structures that represent these two HTML 
constructions are:
\begin{description}
  \titem{\var{Name}\,\$\var{Atts}} (This is a `{\tt \$}' binary
  operator.) Represents an HTML element of name \var{Name} and
  attributes \var{Atts}, were \var{Atts} is a (possibly empty) list of
  attributes, each of them being either an atom or an structure {\tt
    \var{name}=\var{value}}. For example, the term
  \begin{quote}
    \verb+img$[src='images/map.gif',alt='A map',ismap]+
  \end{quote}
  is translated into the HTML source
  \begin{quote}
    \verb+<img src="images/map.gif" alt="A map" ismap>+
  \end{quote}
  Note that HTML is not case-sensitive, so we can use lower-case
  atoms.
  \titem{\var{name}(\var{Text})} (This is a term with functor
  \var{name}/1 and argument \var{Text}) Represents an  HTML
  environment of name \var{name} and included text \var{Text}. For
  example, the term
  \begin{quote}
    \verb+address('clip@dia.fi.upm.es')+
  \end{quote}
  is translated into the HTML source
  \begin{quote}
    \verb+<address>clip@dia.fi.upm.es</address>+
  \end{quote}
  \titem{\var{name}(\var{Atts},\var{Text})} (This is a term with
  functor \var{name}/2 and arguments \var{Atts} and \var{Text})
  Represents an  HTML environment of name \var{name}, attributes
  \var{Atts} and included text \var{Text}. For example, the term
  \begin{quote}
    \verb+a([href='http://www.clip.dia.fi.upm.es/'],'Clip home')+
  \end{quote}
  represents the HTML source
  \begin{quote}
    \verb+<a href="http://www.clip.dia.fi.upm.es/">Clip home</a>+
  \end{quote}
\end{description}

In principle, (almost) any HTML construction can be represented with
these structures\footnote{A notable exception are comments.}, but for the
sake of simplifying HTML creation, more specific structures were
designed.

\subsubsection{Specific Structures}
\label{spestruct}

Most of the names of the structures listed here have been fashioned
after their \LaTeX\cite{latex} equivalent. New structures can be defined
by means of the \hyperref%
{{\tt html\_expansion/2} predicate.}%
{{\tt html\_expansion/2} predicate (see section }{).}%
{expansion} Note that these structures take priority over the above
ones.

\begin{description}
\titem{start} Used at the beginning of a document (translates to
\verb+<html>+).

\titem{end} Used at the end of a document (translates to \verb+</html>+). 

\begin{latexonly}
\titem{--} Produces a horizontal rule (translates to \verb+<hr>+).

\item [\fbox{\tt\char'134\char'134}] Produces a line break
    (translates to \verb+<br>+). 
\end{latexonly}
\begin{htmlonly}
\item [{\tt -{\tt -}}] Produces a horizontal rule (translates to \verb+<hr>+).

\item [\verb+\\+] Produces a line break (translates to \verb+<br>+). 
\end{htmlonly}

\titem{\$} Produces a paragraph break (translates to \verb+<p>+).

\titem{comment(\var{Comment})} Used to insert an HTML comment
(translates to\linebreak\mbox{{\tt <!-- \var{Comment} -->}}).

\titem{title(\var{Title})} Used to give a title to a document
(translates to a \verb+<title>+ environment).

\titem{image(\var{Addr})} Used to include an image of address (URL)
\var{Addr} (translates to an \verb+<img>+ element).

\titem{image(\var{URL},\var{Atts})} Idem with the list of attributes
\var{Atts}.

\titem{ref(\var{Addr},\var{Text})} Produces a hypertext link, \var{Addr}
is the URL of the referenced resource, \var{Text} is the text of the
reference (translates to\linebreak
\verb+<a href="+\var{Addr}\verb+">+\var{Text}\verb+</a>+).

\titem{label(\var{Label},\var{Text})} Labels \var{Text} as a target
destination with label \var{Label} (translates to \verb+<a name="+%
\var{Label}\verb+">+\var{Text}\verb+</a>+).

\titem{heading(\var{N},\var{Text})} Produces a heading of level \var{N}
(\latex{$1 \leq N \leq 6$}\html{1 <= \var{N} <= 6}), \var{Text} is the
  text to be used as heading 
(translates to a \verb+<h+\var{N}\verb+>+ environment).

\titem{itemize(\var{Items})} Produces a list of bulleted items,
\var{Items} is a list of corresponding HTML terms (translates to a
\verb+<ul>+ environment).

\titem{nice\_itemize(\var{Items})} Same as above, but uses nicer
bullets. The bullet used can be changed through the predicate {\tt
  icon\_address/2}.  (See \htmladdnormallink{the source
  file}{source/html.pl} for details.)

\titem{enumerate(\var{Items})} Produces a list of numbered items,
\var{Items} is a list of corresponding HTML terms (translates to an
\verb+<ol>+ environment).

\titem{description(\var{Defs})} Produces a list of defined items,
\var{Defs} is a list whose elements are definitions, each of them
being a Prolog sequence (composed by {\tt ','}/2 operators). The last
element of the sequence is the definition, the other (if any) are the
defined terms (translates to an \verb+<dl>+ environment). \hyperref%
{The example files}%
{Section }{ shows an example that}%
{examples} should clarify this point.

\titem{preformatted(\var{Text})} Used to include preformatted text,
\var{Text} is a list of HTML terms, each element of the list being a
line of the resulting document (translates to a \verb+<pre>+
environment).

\titem{verbatim(\var{Text})} Used to include text verbatim, special
HTML characters ({\tt <,>,\&,"}) are translated into its quoted HTML 
equivalent.

\titem{nl} Used to include a newline in the HTML source (just to
improve human readability).

\titem{begin(\var{Tag},\var{Atts})} It translates to the start of an
HTML environment of name \var{Tag} and attributes \var{Atts}. There
exists also a {\tt begin(\var{Tag})} structure.  Useful, in conjunction
with the next structure, when including in a document output generated
by an existing piece of code (e.g.\ \var{Tag} = {\tt pre}).  Its use is
otherwise discouraged.

\titem{end(\var{Tag})} Translates to the end of an HTML environment of
name \var{Tag}.
\end{description}

\subsubsection{Specific Structures for Forms}
\label{formsstruct}

HTML forms are HTML documents (or parts of HTML documents) which,
when accessed via a form-capable browser (Mosaic, netscape, etc.),
allow the user to perform input through text areas, menus, radio
buttons, etc. This input is not ultimately handled by the browser.
Instead, forms generally have a ``submit'' button. When this button is
pressed, the input provided through the menus, text areas, etc.\ is
sent by the browser to a ``handler'' program, which can be anywhere on
the net. The sending browser then waits for a response from that
program, which comes in the form of a new HTML document.  See for example
\begin{htmlonly}
  \htmladdnormallink{this document}
  {http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html}
\end{htmlonly}
\begin{latexonly}
  \begin{quote}\small\tt
http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/\\
$\hookrightarrow$fill-out-forms/overview.html
  \end{quote}
\end{latexonly}
for details.

The following HTML terms provide a simple way of producing forms from
a Prolog program:

\begin{description}
\label{formcommand}
  \titem{form(\var{Addr})} Specifies the beginning of a form. \var{Addr} is
  the address (URL) of the program that will handle the form (translates
  to\linebreak
  \verb+<form method="POST" action="+\var{Addr}\verb+">+).

  \titem{end\_form} Specifies the end of a form (translates to
  \verb+</form>+)

  \titem{checkbox(\var{Name},\var{State})} Specifies an input of type
  \verb+checkbox+ with name \var{Name}, \var{State}=on if the checkbox is
  initially checked (translates to an \verb+<input>+ element).

  \titem{radio(\var{Name},\var{Value},\var{Selected})} Specifies an
  input of type \verb+radio+ with name \var{Name} (several radio buttons
  which are interlocked must share their name), \var{Value} is the the
  value returned by the button, if \var{Selected}=\var{Value} the button
  is initially checked (translates to an \verb+<input>+ element).

  \titem{input(\var{Type},\var{Atts})} Specifies an input of type
  \var{Type} with a list of attributes \var{Atts}.  Possible values
  of \var{Type} are \verb+text+, \verb+password+, \verb+submit+,
  \verb+reset+, \ldots (translates to an \verb+<input>+ element).

  \titem{textarea(\var{Name},\var{Atts},\var{Text})} Specifies an input
  text area of name \var{Name}. \var{Text} provides the default text to
  be shown in the area, \var{Atts} a list of attributes (translates to
  a \verb+<textarea>+ environment).

  \titem{menu(\var{Name},\var{Atts},\var{Items})} Specifies a menu of
  name \var{Name}, list of attributes \var{Atts} and list of options
  \var{Items}. The elements of the list \var{Items} are marked with the
  prefix operator `{\tt \$}' to indicate that they are selected
  (translates to a \verb+<select>+ environment).

  \titem{form\_reply} This is not HTML, rather, the HTTP protocol
  requires this content descriptor to be used by form handlers when
  replying (translates to ``{\tt Content-type: text/html}'').
\end{description}

\subsubsection{Extending the Package}
\label{expansion}

Along with the obvious solution of changing the source code directly,
the package has a built-in mechanism for extending it by adding clauses to
the following predicate:

\begin{description}
  \titem{html\_expansion(\var{Macro},\var{Translation})} The new HTML
  structure \var{Macro} is equivalent to the standard one
  \var{Translation}. Care must be taken not to transform a structure
  into itself (this would lead to an infinite loop).
\end{description}

The package has these two equivalences predefined (just to make
environments more {\LaTeX}ish):
\begin{verbatim}
html_expansion(bf(X),b(X)).
html_expansion(it(X),i(X)).
\end{verbatim}

As an example, to define structures for the new HTML3 tabbing elements,
one would define the following clauses:
\begin{verbatim}
html_expansion(settab(I),tabstop$[id(I)]).
html_expansion(tabto(I),tab$[to(I)]).
\end{verbatim}

\subsection{Predicates for Producing HTML Executables}
\label{executables}\label{cgibin}

An HTML executable is a standard executable which resides in a directory
which is recognized by the corresponding {\tt httpd} server as
containing executables.  The set of such directories normally includes
{\tt /cgi-bin}, but most {\tt httpd} servers can be configured so that
other directories are also included in this class. CGI stands for
``Common Gateway Interface'', see
\begin{htmlonly}
\htmladdnormallink{this document}
{http://kuhttp.cc.ukans.edu/info/forms/forms-intro.html}
\end{htmlonly}
\begin{latexonly}
\begin{quote} 
\small\tt http://kuhttp.cc.ukans.edu/info/forms/forms-intro.html
\end{quote}
\end{latexonly}
for a good introduction
of CGI scripts and HTML forms.

When access to a standard document is requested by a browser, the {\tt
  httpd} server normally simply returns the contents of the file (which
is normally in HTML format). However, if the requested address
corresponds to a file in an executable directory then the server first
runs the executable and then returns to the requesting browser the
output produced by such run (which is normally in HTML format or
another format which can be handled by the browser).  HTML requests to
executables are generally information requests and Logic Programming is
a natural choice for developing applications capable of fulfilling such
requests.

Developing a WWW executable in Prolog simply amounts to producing a
Prolog program which, when executed, returns an HTML document.  The
formatting facilities presented in the previous sections can be used
for providing such a document. The Prolog executable can be produced
using the usual techniques in Prolog, i.e., through a saved state or
by generating a stand-alone executable. At CLIP we have also developed
a simple package for creating ``Prolog scripts'', i.e., files containing
source code which simply run when executed, in the same way as is
usually done, for example, with shell scripts in UNIX (this package
will be released soon).

The Prolog HTML package also contains some simple predicates which somewhat
simplify the operation of producing a {\tt cgi-bin} executable:

\begin{description}
  \titem{save\_cgi\_bin(\var{Name},\var{EntryPoint})} creates an
  executable corresponding to the current state (using a saved state,
  only available in systems which support them).  The name of the
  executable will be \var{Name} and the entry point when the executable
  is called will be \var{EntryPoint}. The executable will also contain
  an exception handler which produces suitable output (via an HTML
  document) if the application fails or gives run-time errors (see the
  next predicate).  The warning icon used in these messages can be
  changed through the predicate {\tt icon\_address/2}. See
  \htmladdnormallink{the source file}{source/html.pl} for details.

  \titem{html\_protect(\var{Goal})} Protects the execution of the goal
  \var{Goal} so that if it fails or gives run-time errors suitable HTML
  output is produced.

%  \titem{cgi\_bin\_dir(\var{Dir}).} This fact defines the directory
%  in which the\linebreak
%  predicate above saves the executables. \htmlref{The default
%  setting is\linebreak
%  {\tt /usr/local/etc/httpd/cgi-bin/.}}{cgidir}
\end{description}

The following section explains the facilities provided by the package for
creating form handlers, including the parsing of input from
HTML forms.

\subsection{Predicates for Creating Form Handlers}
\label{formhandlers}

An HTML form handler is a special kind of HTML executable that is
accessed when a form is submitted. I.e., it is the program designated
in the \htmlref{form command}{formcommand}. The predicates provided to
simplify this task are:

\begin{description}
  \titem{html\_form\_check} Used to ensure that the executable was
  invoked by an HTML form with a method of ``{\tt POST}''.

  \titem{html\_get\_form\_input(\var{Dic})} Translates input from the
  form to a dictionary \var{Dic} of \var{attribute}=\var{value}
  pairs. It translates empty \var{value}s to {\tt true}.

  \titem{html\_get\_value(\var{Dic},\var{Var},\var{Val})} Gets value
  \var{Val} for attribute \var{Var} in dictionary \var{Dic}. Does not
  fail: value is {\tt ''} if not found.

  \titem{html\_empty\_value(\var{V})} Useful to check that a value
  \var{V} from a text area is empty (can have spaces, newlines and
  linefeeds).

  \titem{default(\var{Val},\var{Default},\var{NewVal})} Useful when the
  executable can be invoked either directly or by a form, to set form
  defaults.  If \var{Val} is empty (because the executable was invoked
  directly) \var{NewVal}=\var{Default}, else \var{NewVal}=\var{Val}.
\end{description}

\section{Example Files}
\label{examples}

We have created several example files to illustrate the use of the
predicates provided by the package and to demonstrate its capabilities.
For each example we list first the Prolog code ({\tt .pl}) and then its
output ({\tt .html}).
\begin{description}
\item[\linktosource{html\_simple.pl}{examples/}] The code shown
  \hyperref{when explaining the use of {\tt output\_html/2}}{in
    section }{}{simplecode}.
\item[\linktosource{html\_simple.html}{examples/}] Shown in the same place.
\item[\linktosource{html\_demo.pl}{examples/}] A file that illustrates
  the creation of HTML pages using \htmlref{the specific
    Prolog HTML structures}{spestruct}\latex{ defined in section
  \ref{spestruct}}.
  \begin{latexonly} \footnotesize
\begin{verbatim}
:- ['/usr/local/lib/prolog/html.pl'].

main :- 
  tell('html_demo.html'),
  output_html([
    start, nl,
    comment('This document was generated from Prolog'),
    title('Sample HTML document generated from Prolog'),
    heading(1,'Sample HTML document'),
    --,
    heading(2,'Miscellaneous'),
    'This is a ',ref('#label',it(reference)),' to ',nl,
    bf(['another ',it(point)]),' in this document.',$,
    'Let''s be ',nl,
    image('http://www.clip.dia.fi.upm.es/images/smile.happy.gif',[alt=':-)']),
    '!',
    preformatted(['These lines',
      ['are ',b(preformatted),'.'],
      'See?']),
    'We have left here a ',strong(free),' variable:',nl,X,$,
    'This is in verbatim: ',nl,
    samp(verbatim('<NOTE> write "&amp;" to insert an &')),\\,
    'But this is not:',
    samp('<NOTE> write "&amp;" to insert an &'),$,
    label(label,['This is the point referenced ',it('above.')]),
    heading(2,'Lists'),
    heading(3,tt(itemize)),
    itemize([one,two,['and ',3]]),
    heading(3,tt(enumerate)),
    enumerate([b(red),i(green),tt(blue)]),
    heading(3,tt(description)),
    description([
      (one,b(two),'Description of one and two'),
      (three,'Idem of three'),
      ['This ',b(also)]]),
    heading(3,'Nice itemize'),
    nice_itemize([pretty,bf(fancy),nice]),
    --,
    address('clip@dia.fi.upm.es'),
    end
  ]),
  told.
\end{verbatim}
  \end{latexonly}

\item[\linktosource{html\_demo.html}{examples/}]
  \begin{latexonly} Output from the above code.\footnotesize
\begin{verbatim}
<html>
<!-- This document was generated from Prolog -->
<title>Sample HTML document generated from Prolog</title>
<h1>Sample HTML document</h1>

<hr>
<h2>Miscellaneous</h2>
This is a <a href="#label"><i>reference</i></a> to 
<b>another <i>point</i></b> in this document.
<p>Let's be 
<img src="http://www.clip.dia.fi.upm.es/images/smile.happy.gif" alt=":-)">!<pre>
These lines
are <b>preformatted</b>.
See?
</pre>We have left here a <strong>free</strong> variable:
<b>**Warning free variable**</b>
<p>This is in verbatim: 
<samp>&lt;NOTE&gt; write &quot;&amp;amp;&quot; to insert an &amp;</samp><br>
But this is not:<samp><NOTE> write "&amp;" to insert an &</samp>
<p><a name="label">This is the point referenced <i>above.</i></a><h2>Lists</h2>
<h3><tt>itemize</tt></h3>
<ul>
<li> one
<li> two
<li> and 3
</ul><h3><tt>enumerate</tt></h3>
<ol>
<li> <b>red</b>
<li> <i>green</i>
<li> <tt>blue</tt>
</ol><h3><tt>description</tt></h3>
<dl>
<dt>one
<dt><b>two</b>
<dd>Description of one and two
<dt>three
<dd>Idem of three
<dd>This <b>also</b>
</dl><h3>Nice itemize</h3>
<dl>
<dd><img src="http://www.clip.dia.fi.upm.es/images/redball.gif" align="bottom"
 alt="*">pretty
<dd><img src="http://www.clip.dia.fi.upm.es/images/redball.gif" align="bottom"
 alt="*"><b>fancy</b>
<dd><img src="http://www.clip.dia.fi.upm.es/images/redball.gif" align="bottom"
 alt="*">nice
</dl>
<hr>
<address>clip@dia.fi.upm.es</address></html>\end{verbatim}
  \end{latexonly}

\item[\linktosource{html\_simple\_form.pl}{examples/}] A simple file
  which illustrates the creation of HTML form handlers using 
  \hyperref{the Prolog HTML structures for forms}{the
    Prolog HTML structures for forms defined in section
    }{}{formsstruct}. It also uses the predicates for \hyperref{producing
    HTML executables}{producing HTML executables (explained in section
    }{)}{executables} and for \hyperref{creating form
    handlers}{creating form handlers (explained in section
    }{)}{formhandlers}. 
  \begin{latexonly} \footnotesize
\begin{verbatim}
:- ['/usr/local/lib/prolog/html.pl'].

main :-
  html_get_form_input(Info),
  html_get_value(Info,person_name,Name),
  response(Name,Response),
  output_html([
    form_reply,
    start,
    image('http://www.clip.dia.fi.upm.es/images/clip.gif'),nl,
    heading(2,'Toy Address Server'),
    --,
    Response,
    form('http://www.clip.dia.fi.upm.es/cgi-bin/html_simple_form'),
    'Click here, enter name, and press return:', 
    \\,
    input(text,[name=person_name,size=20]),
    end_form,
    end]).

response(Name, []) :- 
        html_empty_value(Name), !.
response(Name, ['Available info on ', bf(Name), ':', Info]) :-
        info(Name,Info), !.
response(Name, ['No available info on ', bf(Name), '.']).

info(clip,   '+341-336-7448').
info(manuel, '+341-336-7435').
info(daniel, '+341-336-7448').

:- save_cgi_bin(html_simple_form,main).
\end{verbatim}
\end{latexonly}

\item[\linktosource{html\_simple\_form.html}{examples/}] Output the first time
  the form handler is invoked.
 \begin{latexonly} \footnotesize
\begin{verbatim}
Content-type: text/html

<html><img src="http://www.clip.dia.fi.upm.es/images/clip.gif">
<h2>Toy Address Server</h2>

<hr>
<form method="POST" action="http://www.clip.dia.fi.upm.es/cgi-bin/html_simple_form">
Click here, enter name, and press return:<br>
<input type="text" name="person_name" size="20"></form></html>
\end{verbatim}
  \end{latexonly}

\item[\htmladdnormallink{{\tt html\_simple\_form}}
  {http://www.clip.dia.fi.upm.es/cgi-bin/html_simple_form}] The executable
  produced by {\tt html\_simple\_form.pl}. \html{Try it out!}\latex{You can try
    it out at {\small\tt
      http://www.clip.dia.fi.upm.es/cgi-bin/html\_simple\_form}.}

\item[\linktosource{html\_forms.pl}{examples/}] A more involved
  example of form handling illustrating more uses of \hyperref{the
    Prolog HTML structures for forms}{the Prolog HTML structures for
    forms defined in section }{}{formsstruct}.
  \begin{latexonly} \footnotesize
\begin{verbatim}
:- ['/usr/local/lib/prolog/html.pl'].

main :- 
  html_get_form_input(Info),
  html_get_value(Info,mood,Mood0),
  html_get_value(Info,potatoes,Potatoes),
  html_get_value(Info,pizza,Pizza),
  html_get_value(Info,coke,Coke),
  html_get_value(Info,pass,Password),
  html_get_value(Info,text,Text),
  html_get_value(Info,menu1,Number),
  findall(Color,member(menu2=Color,Info),Colors),
  compute_reply(Mood0,Potatoes,Pizza,Coke,Password,Text,Number,Colors,Reply),
  default(Mood0,happy,Mood),
  output_html([
    form_reply,
    start,
    title('Sample Form generated from Prolog'),
    heading(1,'Sample HTML form'),
    Reply,
    --,
    heading(2,'This is a form:'),
    form('http://www.clip.dia.fi.upm.es/cgi-bin/html_forms'),
    'Please select mood:',\\,
    radio(mood,happy,Mood),nl,
    image('http://www.clip.dia.fi.upm.es/images/smile.happy.gif',
      [align=middle]),
    nl,
    radio(mood,sad,Mood),nl,
    image('http://www.clip.dia.fi.upm.es/images/smile.sad.gif',
      [align=middle]),
    $,
    'What ',strong(do),' you want?',\\,
    checkbox(potatoes,Potatoes), 'Potato(e)s',\\,
    checkbox(pizza,Pizza), 'Pizza',\\,
    checkbox(coke,Coke), 'Coke',
    --,
    'Please write a password:',nl,
    input(password,[name=pass,size=9,maxlength=8]),$,
    textarea(text,[rows=5,cols=20],'Write here something'),$,
    'You can choose here:', menu(menu1,[],[one,$two,three]),$,
    'Also here:', menu(menu2,[multiple],[$red,$green,blue]),$,
    input(submit,[value='Send values']),nl,
    input(reset,[value='Reset values']),
    end_form,
    --,
    address('clip@dia.fi.upm.es'),
    end]).

compute_reply('',_,_,_,_,_,_,_,'') :- !.
compute_reply(Mood,Potatoes,Pizza,Coke,Passwd0,Text0,Number,Colors0,Reply) :-
  compute_food(Potatoes,Pizza,Coke,Food),
  compute_text(Text0,Text),
  compute_password(Passwd0,Passwd),
  compute_colors(Colors0,Colors),
  Reply = [
    --,
    heading(2,'Submitted data:'),
    'You are ',strong(Mood),'.',\\,
    'You want ',strong(Food),\\,
    'The password is ',tt(verbatim(Passwd)),'.',\\,
    'In the text area you wrote: ',tt(verbatim(Text)),$,
    'You chose number ',tt(Number),' and color(s):',
    preformatted(Colors)].

compute_food('','','','no food.').
compute_food(on,'','','potatoes.').
compute_food('',on,'','pizza.').
compute_food('','',on,'coke.').
compute_food(on,on,'','potatoes and pizza.').
compute_food('',on,on,'pizza with coke.').
compute_food(on,'',on,'potatoes with coke.').
compute_food(on,on,on,'potatoes and pizza with coke.').

compute_text(T0,T) :-
  html_empty_value(T0) -> T = '{Nothing}' ; T = T0.

compute_password(P0,P) :-
  P0 = true -> P = '{none}'; P = P0.

compute_colors(C0,C) :-
  C0 = [] -> C = [none] ; C = C0.

member(X,[X|_]).
member(X,[_|Xs]) :- member(X,Xs).

:- save_cgi_bin(html_forms,main).
\end{verbatim}
  \end{latexonly}

\item[\linktosource{html\_forms.html}{examples/}] Output the first time
  the form handler is invoked.
  \begin{latexonly} \footnotesize
\begin{verbatim}
Content-type: text/html

<html><title>Sample Form generated from Prolog</title>
<h1>Sample HTML form</h1>

<hr>
<h2>This is a form:</h2>
<form method="POST" action="http://www.clip.dia.fi.upm.es/cgi-bin/html_forms">
Please select mood:<br>
<input name="mood" type="radio" value="happy" checked>
<img src="http://www.clip.dia.fi.upm.es/images/smile.happy.gif" align="middle">
<input name="mood" type="radio" value="sad">
<img src="http://www.clip.dia.fi.upm.es/images/smile.sad.gif" align="middle">
<p>What <strong>do</strong> you want?<br>
<input name="potatoes" type="checkbox">Potato(e)s<br>
<input name="pizza" type="checkbox">Pizza<br>
<input name="coke" type="checkbox">Coke
<hr>
Please write a password:
<input type="password" name="pass" size="9" maxlength="8">
<p><textarea name="text" rows="5" cols="20">Write here something</textarea>
<p>You can choose here:<select name="menu1"><option>one</option>
<option selected>two</option>
<option>three</option>
</select>
<p>Also here:<select name="menu2" multiple><option selected>red</option>
<option selected>green</option>
<option>blue</option>
</select>
<p><input type="submit" value="Send values">
<input type="reset" value="Reset values"></form>
<hr>
<address>clip@dia.fi.upm.es</address></html>
\end{verbatim}
  \end{latexonly}

\item[\htmladdnormallink{{\tt html\_forms}}
  {http://www.clip.dia.fi.upm.es/cgi-bin/html_forms}] The executable
  produced by {\tt html\_forms.pl}. \html{Try it out!}\latex{You can try
    it out at {\tt http://www.clip.dia.fi.upm.es/cgi-bin/html\_forms}.}

\end{description}

Additionally, you can try out {\tt webchat}, a geographical database\linebreak
server with natural language interface (good old Chat) starting from\linebreak
\htmladdnormallink {{\tt
    http://www.clip.dia.fi.upm.es/miscdocs/webchat\_info.html}}
{http://www.clip.dia.fi.upm.es/miscdocs/webchat\_info.html}.

\section{Coming soon}


The HTML package, as it is right now, allows producing documents and
developing information servers. However, it would also be useful to be
able to directly access the net from a Prolog application, and through
a translation from HTML to Prolog terms, read remote pages and
manipulate their contents, for example to perform an intelligent
keyword analysis of the text within or to find pointers within the
document and in turn follow them. We are working on adding the
following features to support this task:

\begin{itemize}
\item Support for the HTTP protocol through builtins. 
\item A reversible grammar that can also parse HTML documents and turn
them into Prolog terms. 
\item Integration with a ``Concurrency/Distribution'' package.
\end{itemize}

The next release will (hopefully) include these features. We are also
working on a release of our Prolog ``Scripts'' and
Concurency/Distribution packages, which allow writing executable
LP/CLP scripts and concurrent execution, access to remote code,
active objects, etc \cite{ciao-dis-impl-parimp}, with standard LP/CLP
systems.


Please send any comments, bugs, suggestions, to
\htmladdnormallink{{\tt clip@dia.fi.upm.es}}{mailto:clip@dia.fi.upm.es}.

\section{Acknowledgments}

This package has been written by Manuel Hermenegildo and Daniel
Cabeza, using input from L. Naish's forms and F. Bueno's previous Chat
interface. Thanks are due to Pedro L\'{o}pez and other members of the
CLIP group for useful feedback on this document and on the package
itself.


\begin{thebibliography}{1}
\bibitem{ciao-dis-impl-parimp}
D.~Cabeza and M.~Hermenegildo.
\newblock {D}istributed {C}oncurrent {C}onstraint {E}xecution in
               the {CIAO} {S}ystem.
\newblock In {\em Proccedings of the 1995 COMPULOG-NET Workshop on
  Parallelism and Implementation Technologies}, Utrecht, NL, September
1995.
\newblock Available online at 
  \htmladdnormallink{ftp://clip.dia.fi.upm.es/pub/papers/ciao-dis-impl-parimp.ps.Z}{ftp://clip.dia.fi.upm.es/pub/papers/ciao-dis-impl-parimp.ps.Z}.

\bibitem{sicstus}
M. Carlsson.
\newblock {\em {Sics}tus {P}rolog {U}ser's {M}anual}.
\newblock P.O. Box 1263, S-16313 Spanga, Sweden, February 1988.
\newblock Available online at 
  \htmladdnormallink{http://www.sics.se/ps/sicstus/sicstus\_toc.html}%
{http://www.sics.se/ps/sicstus/sicstus\_toc.html}.

\bibitem{ciao-ilps95}
M. Hermenegildo, F. Bueno, M. {Garc\'{\i}a de la Banda}, and G. Puebla.
\newblock {T}he {CIAO} {M}ulti-{D}ialect {C}ompiler and {S}ystem: {A}n
  {E}xperimentation {W}orkbench for {F}uture {(C)LP} {S}ystems.
\newblock In {\em Proccedings of the ILPS'95 Workshop on Visions for the Future
  of Logic Programming}, Portland, Oregon, USA, December 1995.
\newblock Available online at 
  \htmladdnormallink{ftp://clip.dia.fi.upm.es/pub/papers/ciao-report-ilps95ws\_final.ps.Z}{ftp://clip.dia.fi.upm.es/pub/papers/ciao-report-ilps95ws\_final.ps.Z}.

\bibitem{ciao-ppcp}
M. Hermenegildo and the CLIP group.
\newblock {S}ome {M}ethodological {I}ssues in the {D}esign of
  {CIAO} - {A} {G}eneric, {P}arallel {C}oncurrent {C}onstraint {S}ystem.
\newblock In {\em Principles and Practice of Constraint Programming}, LNCS 874,
  pages 123--133. Springer-Verlag, May 1994.
\newblock Available online at 
  \htmladdnormallink{ftp://clip.dia.fi.upm.es/pub/papers/ciao\_ppcp.ps.Z}%
{ftp://clip.dia.fi.upm.es/pub/papers/ciao\_ppcp.ps.Z}.

\bibitem{ngc-and-prolog}
M. Hermenegildo and K. Greene.
\newblock {T}he \&-{P}rolog {S}ystem: {E}xploiting {I}ndependent
  {A}nd-{P}arallelism.
\newblock {\em {N}ew {G}eneration {C}omputing}, 9(3,4):233--257, 1991.
\newblock Available online at 
  \htmladdnormallink{ftp://clip.dia.fi.upm.es/pub/papers/imp\_ngc\_final.ps.Z}
                    {ftp://clip.dia.fi.upm.es/pub/papers/imp\_ngc\_final.ps.Z}.

\bibitem{latex}
L. Lamport.
\newblock {\em LATEX User's Guide \& Reference Manual}.
\newblock Addison-Wesley Publishing Company, Inc., 1986.
\newblock Online information on TeX and LaTeX is available at
  \htmladdnormallink{http://curia.ucc.ie/info/TeX/menu.html}{http://curia.ucc.%
ie/info/TeX/menu.html}.

\end{thebibliography}

\end{document}
