View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker & Richard O'Keefe
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2004-2016, University of Amsterdam
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(sgml_write,
   37          [ html_write/2,               %          +Data, +Options
   38            html_write/3,               % +Stream, +Data, +Options
   39            sgml_write/2,               %          +Data, +Options
   40            sgml_write/3,               % +Stream, +Data, +Options
   41            xml_write/2,                %          +Data, +Options
   42            xml_write/3                 % +Stream, +Data, +Options
   43          ]).   44:- autoload(library(assoc),
   45	    [get_assoc/3,empty_assoc/1,put_assoc/4,list_to_assoc/2]).   46:- autoload(library(error),
   47	    [ must_be/2,
   48	      domain_error/2,
   49	      instantiation_error/1,
   50	      type_error/2,
   51	      representation_error/1
   52	    ]).   53:- autoload(library(gensym),[gensym/2]).   54:- autoload(library(lists),[select/3]).   55:- autoload(library(option),[option/3]).   56:- autoload(library(sgml),[dtd/2,dtd_property/2,xml_name/1]).   57
   58:- predicate_options(xml_write/2, 2, [pass_to(xml_write/3, 3)]).   59:- predicate_options(xml_write/3, 3,
   60                     [ dtd(any),
   61                       doctype(atom),
   62                       public(atom),
   63                       system(atom),
   64                       header(boolean),
   65                       nsmap(list),
   66                       indent(nonneg),
   67                       layout(boolean),
   68                       net(boolean),
   69                       cleanns(boolean)
   70                     ]).   71
   72:- multifile
   73    xmlns/2.                        % NS, URI
   74
   75/** <module> XML/SGML writer module
   76
   77This library provides the inverse functionality   of  the sgml.pl parser
   78library, writing XML, SGML and HTML documents from the parsed output. It
   79is intended to allow rewriting in a  different dialect or encoding or to
   80perform document transformation in Prolog on the parsed representation.
   81
   82The current implementation is  particularly   keen  on getting character
   83encoding and the use of character  entities   right.  Some work has been
   84done providing layout, but space handling in   XML  and SGML make this a
   85very hazardous area.
   86
   87The Prolog-based low-level character and  escape   handling  is the real
   88bottleneck in this library and will probably be   moved  to C in a later
   89stage.
   90
   91@see    library(http/html_write) provides a high-level library for
   92        emitting HTML and XHTML.
   93*/
   94
   95%!  xml_write(+Data, +Options) is det.
   96%!  sgml_write(+Data, +Options) is det.
   97%!  html_write(+Data, +Options) is det.
   98%!  xml_write(+Stream, +Data, +Options) is det.
   99%!  sgml_write(+Stream, +Data, +Options) is det.
  100%!  html_write(+Stream, +Data, +Options) is det.
  101%
  102%   Write a term as created by the SGML/XML parser to a stream in
  103%   SGML or XML format.  Options:
  104%
  105%           * cleanns(Bool)
  106%           If `true` (default), remove duplicate `xmlns`
  107%           attributes.
  108%           * dtd(DTD)
  109%           The DTD.  This is needed for SGML documents that contain
  110%           elements with content model EMPTY.  Characters which may
  111%           not be written directly in the Stream's encoding will be
  112%           written using character data entities from the DTD if at
  113%           all possible, otherwise as numeric character references.
  114%           Note that the DTD will NOT be written out at all; as yet
  115%           there is no way to write out an internal subset,  though
  116%           it would not be hard to add one.
  117%
  118%           * doctype(DocType)
  119%           Document type for the SGML document type declaration.
  120%           If omitted it is taken from the root element.  There is
  121%           never any point in having this be disagree with the
  122%           root element.  A <!DOCTYPE> declaration will be written
  123%           if and only if at least one of doctype(_), public(_), or
  124%           system(_) is provided in Options.
  125%
  126%           * public(PubId)
  127%           The public identifier to be written in the <!DOCTYPE> line.
  128%
  129%           * system(SysId)
  130%           The system identifier to be written in the <!DOCTYPE> line.
  131%
  132%           * header(Bool)
  133%           If Bool is 'false', do not emit the <xml ...> header
  134%           line.  (xml_write/3 only)
  135%
  136%           * nsmap(Map:list(Id=URI))
  137%           When emitting embedded XML, assume these namespaces
  138%           are already defined from the environment.  (xml_write/3
  139%           only).
  140%
  141%           * indent(Indent)
  142%           Indentation of the document (for embedding)
  143%
  144%           * layout(Bool)
  145%           Emit/do not emit layout characters to make output
  146%           readable.
  147%
  148%           * net(Bool)
  149%           Use/do not use Null End Tags.
  150%           For XML, this applies only to empty elements, so you get
  151%
  152%           ==
  153%               <foo/>      (default, net(true))
  154%               <foo></foo> (net(false))
  155%           ==
  156%
  157%           For SGML, this applies to empty elements, so you get
  158%
  159%           ==
  160%               <foo>       (if foo is declared to be EMPTY in the DTD)
  161%               <foo></foo> (default, net(false))
  162%               <foo//      (net(true))
  163%           ==
  164%
  165%           and also to elements with character content not containing /
  166%
  167%           ==
  168%               <b>xxx</b>  (default, net(false))
  169%               <b/xxx/     (net(true)).
  170%           ==
  171%
  172%   Note that if the stream is UTF-8, the system will write special
  173%   characters as UTF-8 sequences, while if it is ISO Latin-1 it
  174%   will use (character) entities if there is a DTD that provides
  175%   them, otherwise it will use numeric character references.
  176
  177xml_write(Data, Options) :-
  178    current_output(Stream),
  179    xml_write(Stream, Data, Options).
  180
  181xml_write(Stream0, Data, Options) :-
  182    fix_user_stream(Stream0, Stream),
  183    (   stream_property(Stream, encoding(text))
  184    ->  set_stream(Stream, encoding(utf8)),
  185        call_cleanup(xml_write(Stream, Data, Options),
  186                     set_stream(Stream, encoding(text)))
  187    ;   new_state(xml, State),
  188        init_state(Options, State),
  189        get_state(State, nsmap, NSMap),
  190        add_missing_namespaces(Data, NSMap, Data1),
  191        emit_xml_encoding(Stream, Options),
  192        emit_doctype(Options, Data, Stream),
  193        write_initial_indent(State, Stream),
  194        emit(Data1, Stream, State)
  195    ).
  196
  197
  198sgml_write(Data, Options) :-
  199    current_output(Stream),
  200    sgml_write(Stream, Data, Options).
  201
  202sgml_write(Stream0, Data, Options) :-
  203    fix_user_stream(Stream0, Stream),
  204    (   stream_property(Stream, encoding(text))
  205    ->  set_stream(Stream, encoding(utf8)),
  206        call_cleanup(sgml_write(Stream, Data, Options),
  207                     set_stream(Stream, encoding(text)))
  208    ;   new_state(sgml, State),
  209        init_state(Options, State),
  210        write_initial_indent(State, Stream),
  211        emit_doctype(Options, Data, Stream),
  212        emit(Data, Stream, State)
  213    ).
  214
  215
  216html_write(Data, Options) :-
  217    current_output(Stream),
  218    html_write(Stream, Data, Options).
  219
  220html_write(Stream, Data, Options) :-
  221    sgml_write(Stream, Data,
  222               [ dtd(html)
  223               | Options
  224               ]).
  225
  226fix_user_stream(user, user_output) :- !.
  227fix_user_stream(Stream, Stream).
  228
  229
  230init_state([], _).
  231init_state([H|T], State) :-
  232    update_state(H, State),
  233    init_state(T, State).
  234
  235update_state(dtd(DTD), State) :-
  236    !,
  237    (   atom(DTD)
  238    ->  dtd(DTD, DTDObj)
  239    ;   DTDObj = DTD
  240    ),
  241    set_state(State, dtd, DTDObj),
  242    dtd_character_entities(DTDObj, EntityMap),
  243    set_state(State, entity_map, EntityMap).
  244update_state(nsmap(Map), State) :-
  245    !,
  246    set_state(State, nsmap, Map).
  247update_state(cleanns(Bool), State) :-
  248    !,
  249    must_be(boolean, Bool),
  250    set_state(State, cleanns, Bool).
  251update_state(indent(Indent), State) :-
  252    !,
  253    must_be(integer, Indent),
  254    set_state(State, indent, Indent).
  255update_state(layout(Bool), State) :-
  256    !,
  257    must_be(boolean, Bool),
  258    set_state(State, layout, Bool).
  259update_state(doctype(_), _) :- !.
  260update_state(public(_),  _) :- !.
  261update_state(system(_),  _) :- !.
  262update_state(net(Bool), State) :-
  263    !,
  264    must_be(boolean, Bool),
  265    set_state(State, net, Bool).
  266update_state(header(Bool), _) :-
  267    !,
  268    must_be(boolean, Bool).
  269update_state(Option, _) :-
  270    domain_error(xml_write_option, Option).
  271
  272%       emit_xml_encoding(+Stream, +Options)
  273%
  274%       Emit the XML fileheader with   encoding information. Setting the
  275%       right encoding on the output stream  must be done before calling
  276%       xml_write/3.
  277
  278emit_xml_encoding(Out, Options) :-
  279    option(header(Hdr), Options, true),
  280    Hdr == true,
  281    !,
  282    stream_property(Out, encoding(Encoding)),
  283    (   (   Encoding == utf8
  284        ;   Encoding == wchar_t
  285        )
  286    ->  format(Out, '<?xml version="1.0" encoding="UTF-8"?>~n~n', [])
  287    ;   Encoding == iso_latin_1
  288    ->  format(Out, '<?xml version="1.0" encoding="ISO-8859-1"?>~n~n', [])
  289    ;   domain_error(xml_encoding, Encoding)
  290    ).
  291emit_xml_encoding(_, _).
  292
  293
  294%!  emit_doctype(+Options, +Data, +Stream)
  295%
  296%   Emit the document-type declaration.
  297%   There is a problem with the first clause if we are emitting SGML:
  298%   the SGML DTDs for HTML up to HTML 4 *do not allow* any 'version'
  299%   attribute; so the only time this is useful is when it is illegal!
  300
  301emit_doctype(_Options, Data, Out) :-
  302    (   Data = [_|_], memberchk(element(html,Att,_), Data)
  303    ;   Data = element(html,Att,_)
  304    ),
  305    memberchk(version=Version, Att),
  306    !,
  307    doctype_literal(Version),
  308    format(Out, '<!DOCTYPE HTML PUBLIC "~w">~n~n', [Version]).
  309emit_doctype(Options, Data, Out) :-
  310    (   memberchk(public(PubId), Options) -> true
  311    ;   PubId = (-)
  312    ),
  313    (   memberchk(system(SysId), Options) -> true
  314    ;   SysId = (-)
  315    ),
  316    \+ (PubId == (-),
  317        SysId == (-),
  318        \+ memberchk(doctype(_), Options)
  319    ),
  320    (   Data = element(DocType,_,_)
  321    ;   Data = [_|_], memberchk(element(DocType,_,_), Data)
  322    ;   memberchk(doctype(DocType), Options)
  323    ),
  324    !,
  325    write_doctype(Out, DocType, PubId, SysId).
  326emit_doctype(_, _, _).
  327
  328write_doctype(_Out, DocType, PubId, SysId) :-
  329    valid_name(DocType),
  330    doctype_literal(PubId),
  331    doctype_literal(SysId),
  332    fail.
  333write_doctype(Out, DocType, -, -) :-
  334    !,
  335    format(Out, '<!DOCTYPE ~w []>~n~n', [DocType]).
  336write_doctype(Out, DocType, -, SysId) :-
  337    !,
  338    format(Out, '<!DOCTYPE ~w SYSTEM "~w">~n~n', [DocType,SysId]).
  339write_doctype(Out, DocType, PubId, -) :-
  340    !,
  341    format(Out, '<!DOCTYPE ~w PUBLIC "~w">~n~n', [DocType,PubId]).
  342write_doctype(Out, DocType, PubId, SysId) :-
  343    format(Out, '<!DOCTYPE ~w PUBLIC "~w" "~w">~n~n', [DocType,PubId,SysId]).
  344
  345
  346%   doctype_literal(+Literal) is det.
  347%
  348%   Raise a domain error if Literal cannot be written as a quoted public
  349%   or system identifier.
  350
  351doctype_literal(-) :-
  352    !.
  353doctype_literal(Literal) :-
  354    format(string(String), '~w', [Literal]),
  355    (   sub_string(String, _, _, _, "\"")
  356    ->  domain_error(doctype_literal, Literal)
  357    ;   true
  358    ).
  359
  360%!  emit(+Element, +Out, +State, +Options)
  361%
  362%   Emit a single element
  363
  364emit(Var, _, _) :-
  365    var(Var),
  366    !,
  367    instantiation_error(Var).
  368emit([], _, _) :- !.
  369emit([H|T], Out, State) :-
  370    !,
  371    emit(H, Out, State),
  372    emit(T, Out, State).
  373emit(CDATA, Out, State) :-
  374    atomic(CDATA),
  375    !,
  376    sgml_write_content(Out, CDATA, State).
  377emit(Element, Out, State) :-
  378    \+ \+ emit_element(Element, Out, State).
  379
  380emit_element(pi(PI), Out, State) :-
  381    !,
  382    get_state(State, entity_map, EntityMap),
  383    (   get_state(State, dialect, xml)
  384    ->  End = '?>'
  385    ;   End = '>'
  386    ),
  387    (   is_text(PI),
  388        sub_atom(PI, _, _, _, End)
  389    ->  domain_error(processing_instruction, PI)
  390    ;   true
  391    ),
  392    write(Out, <?),
  393    write_quoted(Out, PI, '', EntityMap),
  394    (   get_state(State, dialect, xml) ->
  395        write(Out, ?>)
  396    ;   write(Out, >)
  397    ).
  398emit_element(element(Name, Attributes, Content), Out, State) :-
  399    !,
  400    must_be(list, Attributes),
  401    must_be(list, Content),
  402    (   get_state(State, dialect, xml)
  403    ->  update_nsmap(Attributes, CleanAttrs, State),
  404        (   get_state(State, cleanns, true)
  405        ->  WriteAttrs = CleanAttrs
  406        ;   WriteAttrs = Attributes
  407        )
  408    ;   WriteAttrs = Attributes
  409    ),
  410    att_length(WriteAttrs, State, Alen),
  411    (   Alen > 60,
  412        get_state(State, layout, true)
  413    ->  Sep = nl,
  414        AttIndent = 4
  415    ;   Sep = sp,
  416        AttIndent = 0
  417    ),
  418    put_char(Out, '<'),
  419    emit_name(Name, Out, State),
  420    (   AttIndent > 0
  421    ->  \+ \+ ( inc_indent(State, AttIndent),
  422                attributes(WriteAttrs, Sep, Out, State)
  423              )
  424    ;   attributes(WriteAttrs, Sep, Out, State)
  425    ),
  426    content(Content, Out, Name, State).
  427emit_element(E, _, _) :-
  428    type_error(xml_dom, E).
  429
  430attributes([], _, _, _).
  431attributes([H|T], Sep, Out, State) :-
  432    (   Sep == nl
  433    ->  write_indent(State, Out)
  434    ;   put_char(Out, ' ')
  435    ),
  436    attribute(H, Out, State),
  437    attributes(T, Sep, Out, State).
  438
  439attribute(Name=Value, Out, State) :-
  440    emit_name(Name, Out, State),
  441    put_char(Out, =),
  442    sgml_write_attribute(Out, Value, State).
  443
  444att_length(Atts, State, Len) :-
  445    att_length(Atts, State, 0, Len).
  446
  447att_length([], _, Len, Len).
  448att_length([A0|T], State, Len0, Len) :-
  449    alen(A0, State, AL),
  450    Len1 is Len0 + 1 + AL,
  451    att_length(T, State, Len1, Len).
  452
  453alen(ns(NS, _URI):Name=Value, _State, Len) :-
  454    !,
  455    atom_length(Value, AL),
  456    vlen(Name, NL),
  457    atom_length(NS, NsL),
  458    Len is AL+NL+NsL+3.
  459alen(URI:Name=Value, State, Len) :-
  460    !,
  461    atom_length(Value, AL),
  462    vlen(Name, NL),
  463    get_state(State, nsmap, Nsmap),
  464    (   memberchk(NS=URI, Nsmap)
  465    ->  atom_length(NS, NsL)
  466    ;   atom_length(URI, NsL)
  467    ),
  468    Len is AL+NL+NsL+3.
  469alen(Name=Value, _, Len) :-
  470    atom_length(Name, NL),
  471    vlen(Value, AL),
  472    Len is AL+NL+3.
  473
  474vlen(Value, Len) :-
  475    is_list(Value),
  476    !,
  477    vlen_list(Value, 0, Len).
  478vlen(Value, Len) :-
  479    atom_length(Value, Len).
  480
  481vlen_list([], L, L).
  482vlen_list([H|T], L0, L) :-
  483    atom_length(H, HL),
  484    (   L0 == 0
  485    ->  L1 is L0 + HL
  486    ;   L1 is L0 + HL + 1
  487    ),
  488    vlen_list(T, L1, L).
  489
  490
  491emit_name(Name, Out, _) :-
  492    atom(Name),
  493    !,
  494    valid_name(Name),
  495    write(Out, Name).
  496emit_name(ns(NS,_URI):Name, Out, _State) :-
  497    !,
  498    valid_name(Name),
  499    (  NS == ''
  500    -> write(Out, Name)
  501    ;  valid_name(NS),
  502       format(Out, '~w:~w', [NS, Name])
  503    ).
  504emit_name(URI:Name, Out, State) :-
  505    get_state(State, nsmap, NSMap),
  506    memberchk(NS=URI, NSMap),
  507    !,
  508    valid_name(Name),
  509    (   NS == []
  510    ->  write(Out, Name)
  511    ;   valid_name(NS),
  512        format(Out, '~w:~w', [NS, Name])
  513    ).
  514emit_name(Prefix:Name, Out, _) :-
  515    atom(Prefix), atom(Name),
  516    !,
  517    valid_name(Prefix),
  518    valid_name(Name),
  519    format(Out, '~w:~w', [Prefix, Name]).
  520emit_name(Term, Out, _) :-
  521    is_text(Term),
  522    !,
  523    atom_string(Name, Term),
  524    valid_name(Name),
  525    write(Out, Name).
  526emit_name(Term, _, _) :-
  527    type_error(xml_name, Term).
  528
  529%   valid_name(+Name) is det.
  530%
  531%   Raise a domain error if Name is not a valid XML name.  Writing such
  532%   a name would change the structure of the document.
  533
  534valid_name(Name) :-
  535    (   xml_name(Name)
  536    ->  true
  537    ;   domain_error(xml_name, Name)
  538    ).
  539
  540%!  update_nsmap(+Attributes, -Attributes1, !State)
  541%
  542%   Modify the nsmap of State to reflect modifications due to xmlns
  543%   arguments.
  544%
  545%   @arg    Attributes1 is a copy of Attributes with all redundant
  546%           namespace attributes deleted.
  547
  548update_nsmap(Attributes, Attributes1, State) :-
  549    get_state(State, nsmap, Map0),
  550    update_nsmap(Attributes, Attributes1, Map0, Map),
  551    set_state(State, nsmap, Map).
  552
  553update_nsmap([], [], Map, Map).
  554update_nsmap([xmlns:NS=URI|T], Attrs, Map0, Map) :-
  555    !,
  556    (   memberchk(NS=URI, Map0)
  557    ->  update_nsmap(T, Attrs, Map0, Map)
  558    ;   set_nsmap(NS, URI, Map0, Map1),
  559        Attrs = [xmlns:NS=URI|Attrs1],
  560        update_nsmap(T, Attrs1, Map1, Map)
  561    ).
  562update_nsmap([xmlns=URI|T], Attrs, Map0, Map) :-
  563    !,
  564    (   memberchk([]=URI, Map0)
  565    ->  update_nsmap(T, Attrs, Map0, Map)
  566    ;   set_nsmap([], URI, Map0, Map1),
  567        Attrs = [xmlns=URI|Attrs1],
  568        update_nsmap(T, Attrs1, Map1, Map)
  569    ).
  570update_nsmap([H|T0], [H|T], Map0, Map) :-
  571    !,
  572    update_nsmap(T0, T, Map0, Map).
  573
  574set_nsmap(NS, URI, Map0, Map) :-
  575    select(NS=_, Map0, Map1),
  576    !,
  577    Map = [NS=URI|Map1].
  578set_nsmap(NS, URI, Map, [NS=URI|Map]).
  579
  580
  581%!  content(+Content, +Out, +Element, +State, +Options)
  582%
  583%   Emit the content part of a structure  as well as the termination
  584%   for the content. For empty content   we have three versions: XML
  585%   style '/>', SGML declared EMPTY element (nothing) or normal SGML
  586%   element (we must close with the same element name).
  587
  588content([], Out, Element, State) :-    % empty element
  589    !,
  590    (   get_state(State, net, true)
  591    ->  (   get_state(State, dialect, xml) ->
  592            write(Out, />)
  593        ;   empty_element(State, Element) ->
  594            write(Out, >)
  595        ;   write(Out, //)
  596        )
  597    ;/* get_state(State, net, false) */
  598        write(Out, >),
  599        (   get_state(State, dialect, sgml),
  600            empty_element(State, Element)
  601        ->  true
  602        ;   emit_close(Element, Out, State)
  603        )
  604    ).
  605content([CDATA], Out, Element, State) :-
  606    atomic(CDATA),
  607    !,
  608    (   get_state(State, dialect, sgml),
  609        get_state(State, net, true),
  610        \+ sub_atom(CDATA, _, _, _, /),
  611        write_size(CDATA, Len, _H, []),
  612        Len < 20
  613    ->  write(Out, /),
  614        sgml_write_content(Out, CDATA, State),
  615        write(Out, /)
  616    ;   verbatim_element(Element, State)
  617    ->  valid_verbatim(Element, CDATA),
  618        write(Out, >),
  619        write(Out, CDATA),
  620        emit_close(Element, Out, State)
  621    ;/* XML or not NET */
  622            write(Out, >),
  623        sgml_write_content(Out, CDATA, State),
  624        emit_close(Element, Out, State)
  625    ).
  626content(Content, Out, Element, State) :-
  627    get_state(State, layout, true),
  628    /* If xml:space='preserve' is present, */
  629        /* we MUST NOT tamper with white space at all. */
  630        \+ (Element = element(_,Atts,_),
  631        memberchk('xml:space'=preserve, Atts)
  632    ),
  633    element_content(Content, Elements),
  634    !,
  635    format(Out, >, []),
  636    \+ \+ (
  637        inc_indent(State),
  638        write_element_content(Elements, Out, State)
  639    ),
  640    write_indent(State, Out),
  641    emit_close(Element, Out, State).
  642content(Content, Out, Element, State) :-
  643    format(Out, >, []),
  644    write_mixed_content(Content, Out, Element, State),
  645    emit_close(Element, Out, State).
  646
  647verbatim_element(Element, State) :-
  648    verbatim_element(Element),
  649    get_state(State, dtd, DTD),
  650    DTD \== (-),
  651    dtd_property(DTD, doctype(html)).
  652
  653verbatim_element(script).
  654verbatim_element(style).
  655
  656%   valid_verbatim(+Element, +CDATA) is det.
  657%
  658%   The content of script and style elements is not escaped and thus
  659%   may not contain the closing tag.
  660
  661valid_verbatim(Element, CDATA) :-
  662    atomic_list_concat(['</', Element], End),
  663    (   sub_atom_icasechk(CDATA, _, End)
  664    ->  domain_error(cdata, CDATA)
  665    ;   true
  666    ).
  667
  668emit_close(Element, Out, State) :-
  669    write(Out, '</'),
  670    emit_name(Element, Out, State),
  671    write(Out, '>').
  672
  673
  674write_mixed_content([], _, _, _).
  675write_mixed_content([H|T], Out, Element, State) :-
  676    write_mixed_content_element(H, Out, State),
  677    write_mixed_content(T, Out, Element, State).
  678
  679write_mixed_content_element(H, Out, State) :-
  680    (   atom(H)
  681    ->  sgml_write_content(Out, H, State)
  682    ;   string(H)
  683    ->  sgml_write_content(Out, H, State)
  684    ;   functor(H, element, 3)
  685    ->  emit(H, Out, State)
  686    ;   functor(H, pi, 1)
  687    ->  emit(H, Out, State)
  688    ;   var(H)
  689    ->  instantiation_error(H)
  690    ;   H = sdata(Data)             % cannot be written without entity!
  691    ->  print_message(warning, sgml_write(sdata_as_cdata(Data))),
  692        sgml_write_content(Out, Data, State)
  693    ;   type_error(sgml_content, H)
  694    ).
  695
  696
  697element_content([], []).
  698element_content([element(Name,Atts,C)|T0], [element(Name,Atts,C)|T]) :-
  699    !,
  700    element_content(T0, T).
  701element_content([Blank|T0], T) :-
  702    atom(Blank),
  703    atom_codes(Blank, Codes),
  704    all_blanks(Codes),
  705    element_content(T0, T).
  706
  707all_blanks([]).
  708all_blanks([H|T]) :-
  709    code_type(H, space),
  710    all_blanks(T).
  711
  712write_element_content([], _, _).
  713write_element_content([H|T], Out, State) :-
  714    write_indent(State, Out),
  715    emit(H, Out, State),
  716    write_element_content(T, Out, State).
  717
  718
  719                 /*******************************
  720                 *           NAMESPACES         *
  721                 *******************************/
  722
  723%!  add_missing_namespaces(+DOM0, +NsMap, -DOM)
  724%
  725%   Add xmlns:NS=URI definitions to the toplevel element(s) to
  726%   deal with missing namespaces.
  727
  728add_missing_namespaces([], _, []) :- !.
  729add_missing_namespaces([H0|T0], Def, [H|T]) :-
  730    !,
  731    add_missing_namespaces(H0, Def, H),
  732    add_missing_namespaces(T0, Def, T).
  733add_missing_namespaces(Elem0, Def, Elem) :-
  734    Elem0 = element(Name, Atts0, Content),
  735    !,
  736    missing_namespaces(Elem0, Def, Missing),
  737    (   Missing == []
  738    ->  Elem = Elem0
  739    ;   add_missing_ns(Missing, Atts0, Atts),
  740        Elem = element(Name, Atts, Content)
  741    ).
  742add_missing_namespaces(DOM, _, DOM).    % CDATA, etc.
  743
  744add_missing_ns([], Atts, Atts).
  745add_missing_ns([H|T], Atts0, Atts) :-
  746    generate_ns(H, NS, URL),
  747    add_missing_ns(T, [xmlns:NS=URL|Atts0], Atts).
  748
  749%!  generate_ns(+URI, -NS, -URL) is det.
  750%
  751%   Generate a namespace (NS) identifier for URI.
  752
  753generate_ns(URI, NS, URI) :-
  754    xmlns(NS, URI),
  755    !.
  756generate_ns(ns(NS, URI), NS, URI) :-
  757    !.
  758generate_ns(URI, NS, URI) :-
  759    default_ns(URI, NS),
  760    !.
  761generate_ns(URI, NS, URI) :-
  762    gensym(xns, NS).
  763
  764%!  xmlns(?NS, ?URI) is nondet.
  765%
  766%   Hook to define human readable  abbreviations for XML namespaces.
  767%   xml_write/3 tries these locations:
  768%
  769%     1. This hook
  770%     2. Defaults (see below)
  771%     3. rdf_db:ns/2 for RDF-DB integration
  772%
  773%   Default XML namespaces are:
  774%
  775%     | xsi    | http://www.w3.org/2001/XMLSchema-instance |
  776%     | xs     | http://www.w3.org/2001/XMLSchema          |
  777%     | xhtml  | http://www.w3.org/1999/xhtml              |
  778%     | soap11 | http://schemas.xmlsoap.org/soap/envelope/ |
  779%     | soap12 | http://www.w3.org/2003/05/soap-envelope   |
  780%
  781%   @see xml_write/2, rdf_register_ns/2.
  782
  783:- multifile
  784    rdf_db:ns/2.  785
  786default_ns('http://www.w3.org/2001/XMLSchema-instance', xsi).
  787default_ns('http://www.w3.org/2001/XMLSchema',          xs).
  788default_ns('http://www.w3.org/1999/xhtml',              xhtml).
  789default_ns('http://schemas.xmlsoap.org/soap/envelope/', soap11).
  790default_ns('http://www.w3.org/2003/05/soap-envelope',   soap12).
  791default_ns(URI, NS) :-
  792    rdf_db:ns(NS, URI).
  793
  794%!  missing_namespaces(+DOM, +NSMap, -Missing)
  795%
  796%   Return a list of URIs appearing in DOM that are not covered
  797%   by xmlns definitions.
  798
  799missing_namespaces(DOM, Defined, Missing) :-
  800    missing_namespaces(DOM, Defined, [], Missing).
  801
  802missing_namespaces([], _, L, L) :- !.
  803missing_namespaces([H|T], Def, L0, L) :-
  804    !,
  805    missing_namespaces(H, Def, L0, L1),
  806    missing_namespaces(T, Def, L1, L).
  807missing_namespaces(element(Name, Atts, Content), Def, L0, L) :-
  808    !,
  809    update_nsmap(Atts, _, Def, Def1),
  810    missing_ns(Name, Def1, L0, L1),
  811    missing_att_ns(Atts, Def1, L1, L2),
  812    missing_namespaces(Content, Def1, L2, L).
  813missing_namespaces(_, _, L, L).
  814
  815missing_att_ns([], _, M, M).
  816missing_att_ns([Name=_|T], Def, M0, M) :-
  817    missing_ns(Name, Def, M0, M1),
  818    missing_att_ns(T, Def, M1, M).
  819
  820missing_ns(ns(NS, URI):_, Def, M0, M) :-
  821    !,
  822    (   (   memberchk(NS=URI, Def)
  823        ;   memberchk(NS=URI, M0)
  824        )
  825    -> M = M0
  826    ;  NS == ''
  827    -> M = M0
  828    ;  M = [ns(NS, URI)|M0]
  829    ).
  830missing_ns(URI:_, Def, M0, M) :-
  831    !,
  832    (   (   memberchk(_=URI, Def)
  833        ;   memberchk(URI, M0)
  834        ;   URI = xml               % predefined ones
  835        ;   URI = xmlns
  836        )
  837    ->  M = M0
  838    ;   M = [URI|M0]
  839    ).
  840missing_ns(_, _, M, M).
  841
  842                 /*******************************
  843                 *         QUOTED WRITE         *
  844                 *******************************/
  845
  846sgml_write_attribute(Out, Values, State) :-
  847    is_list(Values),
  848    !,
  849    get_state(State, entity_map, EntityMap),
  850    put_char(Out, '"'),
  851    write_quoted_list(Values, Out, '"<&\r\n\t', EntityMap),
  852    put_char(Out, '"').
  853sgml_write_attribute(Out, Value, State) :-
  854    is_text(Value),
  855    !,
  856    get_state(State, entity_map, EntityMap),
  857    xml_chars(State, Value),
  858    put_char(Out, '"'),
  859    write_quoted(Out, Value, '"<&\r\n\t', EntityMap),
  860    put_char(Out, '"').
  861sgml_write_attribute(Out, Value, _State) :-
  862    number(Value),
  863    !,
  864    format(Out, '"~w"', [Value]).
  865sgml_write_attribute(_, Value, _) :-
  866    type_error(sgml_attribute_value, Value).
  867
  868write_quoted_list([], _, _, _).
  869write_quoted_list([H|T], Out, Escape, EntityMap) :-
  870    write_quoted(Out, H, Escape, EntityMap),
  871    (   T == []
  872    ->  true
  873    ;   put_char(Out, ' '),
  874        write_quoted_list(T, Out, Escape, EntityMap)
  875    ).
  876
  877
  878sgml_write_content(Out, Value, State) :-
  879    is_text(Value),
  880    !,
  881    get_state(State, entity_map, EntityMap),
  882    xml_chars(State, Value),
  883    write_quoted(Out, Value, '<&>\r', EntityMap).
  884sgml_write_content(Out, Value, _) :-
  885    write(Out, Value).
  886
  887%   xml_chars(+State, +Text) is det.
  888%
  889%   If we are writing XML, raise a representation error if Text holds
  890%   characters that are not allowed in XML.
  891
  892xml_chars(State, Text) :-
  893    get_state(State, dialect, xml),
  894    !,
  895    (   sub_atom(Text, _, 1, _, C),
  896        char_code(C, Code),
  897        \+ xml_char(Code)
  898    ->  representation_error(xml_char(Code))
  899    ;   true
  900    ).
  901xml_chars(_, _).
  902
  903xml_char(0x9) :- !.
  904xml_char(0xA) :- !.
  905xml_char(0xD) :- !.
  906xml_char(C) :- C >= 0x20, C =< 0xD7FF, !.
  907xml_char(C) :- C >= 0xE000, C =< 0xFFFD, !.
  908xml_char(C) :- C >= 0x10000, C =< 0x10FFFF.
  909
  910is_text(Value) :- atom(Value), !.
  911is_text(Value) :- string(Value), !.
  912
  913write_quoted(Out, Atom, Escape, EntityMap) :-
  914    atom(Atom),
  915    !,
  916    atom_codes(Atom, Codes),
  917    writeq(Codes, Out, Escape, EntityMap).
  918write_quoted(Out, String, Escape, EntityMap) :-
  919    string(String),
  920    !,
  921    string_codes(String, Codes),
  922    writeq(Codes, Out, Escape, EntityMap).
  923write_quoted(_, String, _, _) :-
  924    type_error(atom_or_string, String).
  925
  926
  927%!  writeq(+Text:codes, +Out:stream, +Escape:atom, +Escape:assoc) is det.
  928
  929writeq([], _, _, _).
  930writeq([H|T], Out, Escape, EntityMap) :-
  931    (   char_code(HC, H),
  932        sub_atom(Escape, _, _, _, HC)
  933    ->  write_entity(H, Out, EntityMap)
  934    ;   H >= 256
  935    ->  (   stream_property(Out, encoding(Enc)),
  936            unicode_encoding(Enc)
  937        ->  put_code(Out, H)
  938        ;   write_entity(H, Out, EntityMap)
  939        )
  940    ;   put_code(Out, H)
  941    ),
  942    writeq(T, Out, Escape, EntityMap).
  943
  944unicode_encoding(utf8).
  945unicode_encoding(wchar_t).
  946unicode_encoding(unicode_le).
  947unicode_encoding(unicode_be).
  948
  949write_entity(Code, Out, EntityMap) :-
  950    (   get_assoc(Code, EntityMap, EntityName)
  951    ->  format(Out, '&~w;', [EntityName])
  952    ;   format(Out, '&#x~16R;', [Code])
  953    ).
  954
  955
  956                 /*******************************
  957                 *          INDENTATION         *
  958                 *******************************/
  959
  960write_initial_indent(State, Out) :-
  961    (   get_state(State, indent, Indent),
  962        Indent > 0
  963    ->  emit_indent(Indent, Out)
  964    ;   true
  965    ).
  966
  967write_indent(State, _) :-
  968    get_state(State, layout, false),
  969    !.
  970write_indent(State, Out) :-
  971    get_state(State, indent, Indent),
  972    emit_indent(Indent, Out).
  973
  974emit_indent(Indent, Out) :-
  975    Tabs is Indent // 8,
  976    Spaces is Indent mod 8,
  977    format(Out, '~N', []),
  978    write_n(Tabs, '\t', Out),
  979    write_n(Spaces, ' ', Out).
  980
  981write_n(N, Char, Out) :-
  982    (   N > 0
  983    ->  put_char(Out, Char),
  984        N2 is N - 1,
  985        write_n(N2, Char, Out)
  986    ;   true
  987    ).
  988
  989inc_indent(State) :-
  990    inc_indent(State, 2).
  991
  992inc_indent(State, Inc) :-
  993    state(indent, Arg),
  994    arg(Arg, State, I0),
  995    I is I0 + Inc,
  996    setarg(Arg, State, I).
  997
  998
  999                 /*******************************
 1000                 *         DTD HANDLING         *
 1001                 *******************************/
 1002
 1003%!  empty_element(+State, +Element)
 1004%
 1005%   True if Element is declared  with   EMPTY  content in the (SGML)
 1006%   DTD.
 1007
 1008empty_element(State, Element) :-
 1009    get_state(State, dtd, DTD),
 1010    DTD \== (-),
 1011    dtd_property(DTD, element(Element, _, empty)).
 1012
 1013%!  dtd_character_entities(+DTD, -Map)
 1014%
 1015%   Return an assoc mapping character entities   to their name. Note
 1016%   that the entity representation is a bit dubious. Entities should
 1017%   allow for a wide-character version and avoid the &#..; trick.
 1018
 1019dtd_character_entities(DTD, Map) :-
 1020    empty_assoc(Empty),
 1021    dtd_property(DTD, entities(Entities)),
 1022    fill_entity_map(Entities, DTD, Empty, Map).
 1023
 1024fill_entity_map([], _, Map, Map).
 1025fill_entity_map([H|T], DTD, Map0, Map) :-
 1026    (   dtd_property(DTD, entity(H, CharEntity)),
 1027        atom(CharEntity),
 1028        (   sub_atom(CharEntity, 0, _, _, '&#'),
 1029            sub_atom(CharEntity, _, _, 0, ';')
 1030        ->  sub_atom(CharEntity, 2, _, 1, Name),
 1031            atom_number(Name, Code)
 1032        ;   atom_length(CharEntity, 1),
 1033            char_code(CharEntity, Code)
 1034        )
 1035    ->  put_assoc(Code, Map0, H, Map1),
 1036        fill_entity_map(T, DTD, Map1, Map)
 1037    ;   fill_entity_map(T, DTD, Map0, Map)
 1038    ).
 1039
 1040
 1041
 1042                 /*******************************
 1043                 *            FIELDS            *
 1044                 *******************************/
 1045
 1046state(indent,     1).                   % current indentation
 1047state(layout,     2).                   % use layout (true/false)
 1048state(dtd,        3).                   % DTD for entity names
 1049state(entity_map, 4).                   % compiled entity-map
 1050state(dialect,    5).                   % xml/sgml
 1051state(nsmap,      6).                   % defined namespaces
 1052state(net,        7).                   % Should null end-tags be used?
 1053state(cleanns,    8).                   % Remove duplicate xmlns declarations
 1054
 1055new_state(Dialect,
 1056    state(
 1057        0,              % indent
 1058        true,           % layout
 1059        -,              % DTD
 1060        EntityMap,      % entity_map
 1061        Dialect,        % dialect
 1062        [],             % NS=Full map
 1063        Net,            % Null End-Tags?
 1064        true            % Remove duplicate xmlns declarations
 1065    )) :-
 1066    (   Dialect == sgml
 1067    ->  Net = false,
 1068        empty_assoc(EntityMap)
 1069    ;   Net = true,
 1070        xml_entities(EntityMap)
 1071    ).
 1072
 1073get_state(State, Field, Value) :-
 1074    state(Field, Arg),
 1075    arg(Arg, State, Value).
 1076
 1077set_state(State, Field, Value) :-
 1078    state(Field, Arg),
 1079    setarg(Arg, State, Value).
 1080
 1081term_expansion(xml_entities(map),
 1082               xml_entities(Map)) :-
 1083    list_to_assoc([ 0'< - lt,
 1084                    0'& - amp,
 1085                    0'> - gt,
 1086                    0'\' - apos,
 1087                    0'\" - quot
 1088                  ], Map).
 1089xml_entities(map).
 1090
 1091                 /*******************************
 1092                 *            MESSAGES          *
 1093                 *******************************/
 1094
 1095:- multifile
 1096    prolog:message/3. 1097
 1098prolog:message(sgml_write(sdata_as_cdata(Data))) -->
 1099    [ 'SGML-write: emitting SDATA as CDATA: "~p"'-[Data] ]