2 * \file output_xhtml.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * This code is based upon output_docbook.cpp
10 * Full author contact details are available in file CREDITS.
15 #include "output_xhtml.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphList.h"
26 #include "ParagraphParameters.h"
29 #include "TextClass.h"
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/lassert.h"
34 #include "support/lstrings.h"
35 #include "support/textutils.h"
40 using namespace lyx::support;
46 docstring escapeChar(char_type c, XHTMLStream::EscapeSettings e)
50 case XHTMLStream::ESCAPE_NONE:
53 case XHTMLStream::ESCAPE_ALL:
57 } else if (c == '>') {
62 case XHTMLStream::ESCAPE_AND:
73 // escape what needs escaping
74 docstring htmlize(docstring const & str, XHTMLStream::EscapeSettings e) {
76 docstring::const_iterator it = str.begin();
77 docstring::const_iterator en = str.end();
78 for (; it != en; ++it)
79 d << escapeChar(*it, e);
84 string escapeChar(char c, XHTMLStream::EscapeSettings e)
88 case XHTMLStream::ESCAPE_NONE:
91 case XHTMLStream::ESCAPE_ALL:
95 } else if (c == '>') {
100 case XHTMLStream::ESCAPE_AND:
111 // escape what needs escaping
112 string htmlize(string const & str, XHTMLStream::EscapeSettings e) {
114 string::const_iterator it = str.begin();
115 string::const_iterator en = str.end();
116 for (; it != en; ++it)
117 d << escapeChar(*it, e);
122 string cleanAttr(string const & str)
125 string::const_iterator it = str.begin();
126 string::const_iterator en = str.end();
127 for (; it != en; ++it)
128 newname += isalnum(*it) ? *it : '_';
133 docstring cleanAttr(docstring const & str)
136 docstring::const_iterator it = str.begin();
137 docstring::const_iterator en = str.end();
138 for (; it != en; ++it) {
139 char_type const c = *it;
140 newname += isAlnumASCII(c) ? c : char_type('_');
146 bool isFontTag(string const & s)
148 return s == "em" || s == "strong"; // others?
152 docstring StartTag::asTag() const
154 string output = "<" + tag_;
156 output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE);
158 return from_utf8(output);
162 docstring StartTag::asEndTag() const
164 string output = "</" + tag_ + ">";
165 return from_utf8(output);
169 docstring EndTag::asEndTag() const
171 string output = "</" + tag_ + ">";
172 return from_utf8(output);
176 docstring CompTag::asTag() const
178 string output = "<" + tag_;
180 output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE);
182 return from_utf8(output);
189 ////////////////////////////////////////////////////////////////
193 ////////////////////////////////////////////////////////////////
195 XHTMLStream::XHTMLStream(odocstream & os)
196 : os_(os), escape_(ESCAPE_ALL)
200 void XHTMLStream::cr()
203 os_ << from_ascii("\n");
207 void XHTMLStream::writeError(std::string const & s)
210 os_ << from_utf8("<!-- Output Error: " + s + " -->");
214 bool XHTMLStream::closeFontTags()
216 if (tag_stack_.empty())
218 // first, we close any open font tags we can close
219 html::StartTag curtag = tag_stack_.back();
220 while (html::isFontTag(curtag.tag_)) {
221 os_ << curtag.asEndTag();
222 tag_stack_.pop_back();
223 if (tag_stack_.empty())
224 // this probably shouldn't happen, since then the
225 // font tags weren't in any other tag. but that
226 // problem will likely be caught elsewhere.
228 curtag = tag_stack_.back();
230 // so we've hit a non-font tag. let's see if any of the
231 // remaining tags are font tags.
232 TagStack::const_iterator it = tag_stack_.begin();
233 TagStack::const_iterator en = tag_stack_.end();
234 bool noFontTags = true;
235 for (; it != en; ++it) {
236 if (html::isFontTag(it->tag_)) {
237 writeError("Font tag `" + it->tag_ + "' still open in closeFontTags().\n"
238 "This is likely not a problem, but you might want to check.");
246 void XHTMLStream::clearTagDeque()
248 while (!pending_tags_.empty()) {
249 html::StartTag const & tag = pending_tags_.front();
252 tag_stack_.push_back(tag);
253 pending_tags_.pop_front();
258 XHTMLStream & XHTMLStream::operator<<(docstring const & d)
261 os_ << html::htmlize(d, escape_);
262 escape_ = ESCAPE_ALL;
267 XHTMLStream & XHTMLStream::operator<<(const char * s)
270 docstring const d = from_ascii(s);
271 os_ << html::htmlize(d, escape_);
272 escape_ = ESCAPE_ALL;
277 XHTMLStream & XHTMLStream::operator<<(char_type c)
280 os_ << html::escapeChar(c, escape_);
281 escape_ = ESCAPE_ALL;
286 XHTMLStream & XHTMLStream::operator<<(char c)
289 string const d = html::escapeChar(c, escape_);
290 escape_ = ESCAPE_ALL;
295 XHTMLStream & XHTMLStream::operator<<(int i)
299 escape_ = ESCAPE_ALL;
304 XHTMLStream & XHTMLStream::operator<<(EscapeSettings e)
311 XHTMLStream & XHTMLStream::operator<<(html::StartTag const & tag)
313 if (tag.tag_.empty())
315 pending_tags_.push_back(tag);
322 XHTMLStream & XHTMLStream::operator<<(html::CompTag const & tag)
324 if (tag.tag_.empty())
334 bool XHTMLStream::isTagOpen(string const & stag)
336 TagStack::const_iterator sit = tag_stack_.begin();
337 TagStack::const_iterator const sen = tag_stack_.end();
338 for (; sit != sen; ++sit)
339 if (sit->tag_ == stag)
345 // this is complicated, because we want to make sure that
346 // everything is properly nested. the code ought to make
347 // sure of that, but we won't assert (yet) if we run into
348 // a problem. we'll just output error messages and try our
349 // best to make things work.
350 XHTMLStream & XHTMLStream::operator<<(html::EndTag const & etag)
352 if (etag.tag_.empty())
355 // make sure there are tags to be closed
356 if (tag_stack_.empty()) {
357 writeError("Tried to close `" + etag.tag_
358 + "' when no tags were open!");
362 // first make sure we're not closing an empty tag
363 if (!pending_tags_.empty()) {
364 html::StartTag const & stag = pending_tags_.back();
365 if (etag.tag_ == stag.tag_) {
366 // we have <tag></tag>, so we discard it and remove it
367 // from the pending_tags_.
368 pending_tags_.pop_back();
371 // there is a pending tag that isn't the one we are trying
373 // is this tag itself pending?
374 // non-const iterators because we may call erase().
375 TagStack::iterator dit = pending_tags_.begin();
376 TagStack::iterator const den = pending_tags_.end();
377 for (; dit != den; ++dit) {
378 if (dit->tag_ == etag.tag_) {
379 // it was pending, so we just erase it
380 writeError("Tried to close pending tag `" + etag.tag_
381 + "' when other tags were pending. Last pending tag is `"
382 + pending_tags_.back().tag_ + "'. Tag discarded.");
383 pending_tags_.erase(dit);
387 // so etag isn't itself pending. is it even open?
388 if (!isTagOpen(etag.tag_)) {
389 writeError("Tried to close `" + etag.tag_
390 + "' when tag was not open. Tag discarded.");
393 // ok, so etag is open.
394 // our strategy will be as below: we will do what we need to
395 // do to close this tag.
396 string estr = "Closing tag `" + etag.tag_
397 + "' when other tags are pending. Discarded pending tags:\n";
398 for (dit = pending_tags_.begin(); dit != den; ++dit)
399 estr += dit->tag_ + "\n";
401 // clear the pending tags...
402 pending_tags_.clear();
403 // ...and then just fall through.
406 // is the tag we are closing the last one we opened?
407 if (etag.tag_ == tag_stack_.back().tag_) {
409 os_ << etag.asEndTag();
410 // ...and forget about it
411 tag_stack_.pop_back();
415 // we are trying to close a tag other than the one last opened.
416 // let's first see if this particular tag is still open somehow.
417 if (!isTagOpen(etag.tag_)) {
418 writeError("Tried to close `" + etag.tag_
419 + "' when tag was not open. Tag discarded.");
423 // so the tag was opened, but other tags have been opened since
424 // and not yet closed.
425 // if it's a font tag, though...
426 if (html::isFontTag(etag.tag_)) {
427 // it won't be a problem if the other tags open since this one
428 // are also font tags.
429 TagStack::const_reverse_iterator rit = tag_stack_.rbegin();
430 TagStack::const_reverse_iterator ren = tag_stack_.rend();
431 for (; rit != ren; ++rit) {
432 if (rit->tag_ == etag.tag_)
434 if (!html::isFontTag(rit->tag_)) {
435 // we'll just leave it and, presumably, have to close it later.
436 writeError("Unable to close font tag `" + etag.tag_
437 + "' due to open non-font tag `" + rit->tag_ + "'.");
443 // <em>this is <strong>bold
444 // and are being asked to closed em. we want:
445 // <em>this is <strong>bold</strong></em><strong>
446 // first, we close the intervening tags...
447 html::StartTag curtag = tag_stack_.back();
448 // ...remembering them in a stack.
450 while (curtag.tag_ != etag.tag_) {
451 os_ << curtag.asEndTag();
452 fontstack.push_back(curtag);
453 tag_stack_.pop_back();
454 curtag = tag_stack_.back();
456 // now close our tag...
457 os_ << etag.asEndTag();
458 tag_stack_.pop_back();
460 // ...and restore the other tags.
461 rit = fontstack.rbegin();
462 ren = fontstack.rend();
463 for (; rit != ren; ++rit)
464 pending_tags_.push_back(*rit);
468 // it wasn't a font tag.
469 // so other tags were opened before this one and not properly closed.
470 // so we'll close them, too. that may cause other issues later, but it
471 // at least guarantees proper nesting.
472 writeError("Closing tag `" + etag.tag_
473 + "' when other tags are open, namely:");
474 html::StartTag curtag = tag_stack_.back();
475 while (curtag.tag_ != etag.tag_) {
476 writeError(curtag.tag_);
477 os_ << curtag.asEndTag();
478 tag_stack_.pop_back();
479 curtag = tag_stack_.back();
481 // curtag is now the one we actually want.
482 os_ << curtag.asEndTag();
483 tag_stack_.pop_back();
488 // End code for XHTMLStream
492 // convenience functions
494 inline void openTag(XHTMLStream & xs, Layout const & lay)
496 xs << html::StartTag(lay.htmltag(), lay.htmlattr());
500 void openTag(XHTMLStream & xs, Layout const & lay,
501 ParagraphParameters const & params)
503 // FIXME Are there other things we should handle here?
504 string const align = alignmentToCSS(params.align());
509 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
510 xs << html::StartTag(lay.htmltag(), attrs);
514 inline void closeTag(XHTMLStream & xs, Layout const & lay)
516 xs << html::EndTag(lay.htmltag());
520 inline void openLabelTag(XHTMLStream & xs, Layout const & lay)
522 xs << html::StartTag(lay.htmllabeltag(), lay.htmllabelattr());
526 inline void closeLabelTag(XHTMLStream & xs, Layout const & lay)
528 xs << html::EndTag(lay.htmllabeltag());
532 inline void openItemTag(XHTMLStream & xs, Layout const & lay)
534 xs << html::StartTag(lay.htmlitemtag(), lay.htmlitemattr(), true);
538 void openItemTag(XHTMLStream & xs, Layout const & lay,
539 ParagraphParameters const & params)
541 // FIXME Are there other things we should handle here?
542 string const align = alignmentToCSS(params.align());
544 openItemTag(xs, lay);
547 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
548 xs << html::StartTag(lay.htmlitemtag(), attrs);
552 inline void closeItemTag(XHTMLStream & xs, Layout const & lay)
554 xs << html::EndTag(lay.htmlitemtag());
557 // end of convenience functions
559 ParagraphList::const_iterator searchParagraphHtml(
560 ParagraphList::const_iterator p,
561 ParagraphList::const_iterator const & pend)
563 for (++p; p != pend && p->layout().latextype == LATEX_PARAGRAPH; ++p)
570 ParagraphList::const_iterator searchEnvironmentHtml(
571 ParagraphList::const_iterator const pstart,
572 ParagraphList::const_iterator const & pend)
574 ParagraphList::const_iterator p = pstart;
575 Layout const & bstyle = p->layout();
576 size_t const depth = p->params().depth();
577 for (++p; p != pend; ++p) {
578 Layout const & style = p->layout();
579 // It shouldn't happen that e.g. a section command occurs inside
580 // a quotation environment, at a higher depth, but as of 6/2009,
581 // it can happen. We pretend that it's just at lowest depth.
582 if (style.latextype == LATEX_COMMAND)
584 // If depth is down, we're done
585 if (p->params().depth() < depth)
587 // If depth is up, we're not done
588 if (p->params().depth() > depth)
590 // Now we know we are at the same depth
591 if (style.latextype == LATEX_PARAGRAPH
592 || style.latexname() != bstyle.latexname())
599 ParagraphList::const_iterator makeParagraphs(Buffer const & buf,
601 OutputParams const & runparams,
603 ParagraphList::const_iterator const & pbegin,
604 ParagraphList::const_iterator const & pend)
606 ParagraphList::const_iterator const begin = text.paragraphs().begin();
607 ParagraphList::const_iterator par = pbegin;
608 for (; par != pend; ++par) {
609 Layout const & lay = par->layout();
610 if (!lay.counter.empty())
611 buf.params().documentClass().counters().step(lay.counter, OutputUpdate);
612 // FIXME We should see if there's a label to be output and
613 // do something with it.
617 // If we are already in a paragraph, and this is the first one, then we
618 // do not want to open the paragraph tag.
619 // we also do not want to open it if the current layout does not permit
620 // multiple paragraphs.
621 bool const opened = runparams.html_make_pars &&
622 (par != pbegin || !runparams.html_in_par);
624 openTag(xs, lay, par->params());
625 docstring const deferred =
626 par->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, par)));
628 // We want to issue the closing tag if either:
629 // (i) We opened it, and either html_in_par is false,
630 // or we're not in the last paragraph, anyway.
631 // (ii) We didn't open it and html_in_par is true,
632 // but we are in the first par, and there is a next par.
633 ParagraphList::const_iterator nextpar = par;
635 bool const needclose =
636 (opened && (!runparams.html_in_par || nextpar != pend))
637 || (!opened && runparams.html_in_par && par == pbegin && nextpar != pend);
642 if (!deferred.empty()) {
643 xs << XHTMLStream::ESCAPE_NONE << deferred;
651 ParagraphList::const_iterator makeBibliography(Buffer const & buf,
653 OutputParams const & runparams,
655 ParagraphList::const_iterator const & pbegin,
656 ParagraphList::const_iterator const & pend)
659 // Use TextClass::htmlTOCLayout() to figure out how we should look.
660 xs << html::StartTag("h2", "class='bibliography'");
661 xs << pbegin->layout().labelstring(false);
662 xs << html::EndTag("h2");
664 xs << html::StartTag("div", "class='bibliography'");
666 makeParagraphs(buf, xs, runparams, text, pbegin, pend);
667 xs << html::EndTag("div");
672 bool isNormalEnv(Layout const & lay)
674 return lay.latextype == LATEX_ENVIRONMENT
675 || lay.latextype == LATEX_BIB_ENVIRONMENT;
679 ParagraphList::const_iterator makeEnvironmentHtml(Buffer const & buf,
681 OutputParams const & runparams,
683 ParagraphList::const_iterator const & pbegin,
684 ParagraphList::const_iterator const & pend)
686 ParagraphList::const_iterator const begin = text.paragraphs().begin();
687 ParagraphList::const_iterator par = pbegin;
688 Layout const & bstyle = par->layout();
689 depth_type const origdepth = pbegin->params().depth();
691 // open tag for this environment
695 // we will on occasion need to remember a layout from before.
696 Layout const * lastlay = 0;
698 while (par != pend) {
699 Layout const & style = par->layout();
700 // the counter only gets stepped if we're in some kind of list,
701 // or if it's the first time through.
702 // note that enum, etc, are handled automatically.
703 // FIXME There may be a bug here about user defined enumeration
704 // types. If so, then we'll need to take the counter and add "i",
705 // "ii", etc, as with enum.
706 Counters & cnts = buf.params().documentClass().counters();
707 docstring const & cntr = style.counter;
708 if (!style.counter.empty()
709 && (par == pbegin || !isNormalEnv(style))
710 && cnts.hasCounter(cntr)
712 cnts.step(cntr, OutputUpdate);
713 ParagraphList::const_iterator send;
714 // this will be positive, if we want to skip the initial word
715 // (if it's been taken for the label).
718 switch (style.latextype) {
719 case LATEX_ENVIRONMENT:
720 case LATEX_LIST_ENVIRONMENT:
721 case LATEX_ITEM_ENVIRONMENT: {
722 // There are two possiblities in this case.
723 // One is that we are still in the environment in which we
724 // started---which we will be if the depth is the same.
725 if (par->params().depth() == origdepth) {
726 LASSERT(bstyle == style, /* */);
728 closeItemTag(xs, *lastlay);
732 bool const labelfirst = style.htmllabelfirst();
734 openItemTag(xs, style, par->params());
737 if (style.labeltype != LABEL_NO_LABEL &&
738 style.htmllabeltag() != "NONE") {
739 if (isNormalEnv(style)) {
740 // in this case, we print the label only for the first
741 // paragraph (as in a theorem).
743 docstring const lbl =
744 pbegin->params().labelString();
746 openLabelTag(xs, style);
748 closeLabelTag(xs, style);
752 } else { // some kind of list
753 if (style.labeltype == LABEL_MANUAL) {
754 openLabelTag(xs, style);
755 sep = par->firstWordLyXHTML(xs, runparams);
756 closeLabelTag(xs, style);
760 openLabelTag(xs, style);
761 xs << par->params().labelString();
762 closeLabelTag(xs, style);
766 } // end label output
769 openItemTag(xs, style, par->params());
771 par->simpleLyXHTMLOnePar(buf, xs, runparams,
772 text.outerFont(distance(begin, par)), sep);
775 // We may not want to close the tag yet, in particular:
776 // If we're not at the end...
778 // and are doing items...
779 && !isNormalEnv(style)
780 // and if the depth has changed...
781 && par->params().depth() != origdepth) {
782 // then we'll save this layout for later, and close it when
783 // we get another item.
786 closeItemTag(xs, style);
789 // The other possibility is that the depth has increased, in which
790 // case we need to recurse.
792 send = searchEnvironmentHtml(par, pend);
793 par = makeEnvironmentHtml(buf, xs, runparams, text, par, send);
797 case LATEX_PARAGRAPH:
798 send = searchParagraphHtml(par, pend);
799 par = makeParagraphs(buf, xs, runparams, text, par, send);
802 case LATEX_BIB_ENVIRONMENT:
805 par = makeParagraphs(buf, xs, runparams, text, par, send);
815 closeItemTag(xs, *lastlay);
816 closeTag(xs, bstyle);
822 void makeCommand(Buffer const & buf,
824 OutputParams const & runparams,
826 ParagraphList::const_iterator const & pbegin)
828 Layout const & style = pbegin->layout();
829 if (!style.counter.empty())
830 buf.params().documentClass().counters().step(style.counter, OutputUpdate);
832 openTag(xs, style, pbegin->params());
834 // Label around sectioning number:
835 // FIXME Probably need to account for LABEL_MANUAL
836 if (style.labeltype != LABEL_NO_LABEL) {
837 openLabelTag(xs, style);
838 xs << pbegin->params().labelString();
839 closeLabelTag(xs, style);
840 // Otherwise the label might run together with the text
841 xs << from_ascii(" ");
844 ParagraphList::const_iterator const begin = text.paragraphs().begin();
845 pbegin->simpleLyXHTMLOnePar(buf, xs, runparams,
846 text.outerFont(distance(begin, pbegin)));
851 } // end anonymous namespace
854 void xhtmlParagraphs(Text const & text,
857 OutputParams const & runparams)
859 ParagraphList const & paragraphs = text.paragraphs();
860 ParagraphList::const_iterator par = paragraphs.begin();
861 ParagraphList::const_iterator pend = paragraphs.end();
863 OutputParams ourparams = runparams;
864 while (par != pend) {
865 if (par->params().startOfAppendix()) {
866 // FIXME: only the counter corresponding to toplevel
867 // sectioning should be reset
868 Counters & cnts = buf.masterBuffer()->params().documentClass().counters();
872 Layout const & style = par->layout();
873 ParagraphList::const_iterator lastpar = par;
874 ParagraphList::const_iterator send;
876 switch (style.latextype) {
877 case LATEX_COMMAND: {
878 // The files with which we are working never have more than
879 // one paragraph in a command structure.
881 // if (ourparams.html_in_par)
882 // fix it so we don't get sections inside standard, e.g.
883 // note that we may then need to make runparams not const, so we
884 // can communicate that back.
885 // FIXME Maybe this fix should be in the routines themselves, in case
886 // they are called from elsewhere.
887 makeCommand(buf, xs, ourparams, text, par);
891 case LATEX_ENVIRONMENT:
892 case LATEX_LIST_ENVIRONMENT:
893 case LATEX_ITEM_ENVIRONMENT: {
894 // FIXME Same fix here.
895 send = searchEnvironmentHtml(par, pend);
896 par = makeEnvironmentHtml(buf, xs, ourparams, text, par, send);
899 case LATEX_BIB_ENVIRONMENT: {
900 // FIXME Same fix here.
901 send = searchEnvironmentHtml(par, pend);
902 par = makeBibliography(buf, xs, ourparams, text, par, send);
905 case LATEX_PARAGRAPH:
906 send = searchParagraphHtml(par, pend);
907 par = makeParagraphs(buf, xs, ourparams, text, par, send);
911 // makeEnvironment may process more than one paragraphs and bypass pend
912 if (distance(lastpar, par) >= distance(lastpar, pend))
918 string alignmentToCSS(LyXAlignment align) {
920 case LYX_ALIGN_BLOCK:
921 // we are NOT going to use text-align: justify!!
924 case LYX_ALIGN_RIGHT:
926 case LYX_ALIGN_CENTER: