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::writeError(std::string const & s)
203 os_ << from_utf8("<!-- Output Error: " + s + " -->");
207 bool XHTMLStream::closeFontTags()
209 if (tag_stack_.empty())
211 // first, we close any open font tags we can close
212 html::StartTag curtag = tag_stack_.back();
213 while (html::isFontTag(curtag.tag_)) {
214 os_ << curtag.asEndTag();
215 tag_stack_.pop_back();
216 if (tag_stack_.empty())
217 // this probably shouldn't happen, since then the
218 // font tags weren't in any other tag. but that
219 // problem will likely be caught elsewhere.
221 curtag = tag_stack_.back();
223 // so we've hit a non-font tag. let's see if any of the
224 // remaining tags are font tags.
225 TagStack::const_iterator it = tag_stack_.begin();
226 TagStack::const_iterator en = tag_stack_.end();
227 bool noFontTags = true;
228 for (; it != en; ++it) {
229 if (html::isFontTag(it->tag_)) {
230 writeError("Font tag `" + it->tag_ + "' still open in closeFontTags().\n"
231 "This is likely not a problem, but you might want to check.");
239 void XHTMLStream::clearTagDeque()
241 while (!pending_tags_.empty()) {
242 html::StartTag const & tag = pending_tags_.front();
245 tag_stack_.push_back(tag);
246 pending_tags_.pop_front();
251 XHTMLStream & XHTMLStream::operator<<(docstring const & d)
254 os_ << html::htmlize(d, escape_);
255 escape_ = ESCAPE_ALL;
260 XHTMLStream & XHTMLStream::operator<<(const char * s)
263 docstring const d = from_ascii(s);
264 os_ << html::htmlize(d, escape_);
265 escape_ = ESCAPE_ALL;
270 XHTMLStream & XHTMLStream::operator<<(char_type c)
273 os_ << html::escapeChar(c, escape_);
274 escape_ = ESCAPE_ALL;
279 XHTMLStream & XHTMLStream::operator<<(char c)
282 string const d = html::escapeChar(c, escape_);
283 escape_ = ESCAPE_ALL;
288 XHTMLStream & XHTMLStream::operator<<(int i)
292 escape_ = ESCAPE_ALL;
297 XHTMLStream & XHTMLStream::operator<<(EscapeSettings e)
304 XHTMLStream & XHTMLStream::operator<<(html::StartTag const & tag)
306 if (tag.tag_.empty())
308 pending_tags_.push_back(tag);
315 XHTMLStream & XHTMLStream::operator<<(html::CompTag const & tag)
317 if (tag.tag_.empty())
327 XHTMLStream & XHTMLStream::operator<<(html::CR const &)
330 os_ << from_ascii("\n");
335 bool XHTMLStream::isTagOpen(string const & stag)
337 TagStack::const_iterator sit = tag_stack_.begin();
338 TagStack::const_iterator const sen = tag_stack_.end();
339 for (; sit != sen; ++sit)
340 if (sit->tag_ == stag)
346 // this is complicated, because we want to make sure that
347 // everything is properly nested. the code ought to make
348 // sure of that, but we won't assert (yet) if we run into
349 // a problem. we'll just output error messages and try our
350 // best to make things work.
351 XHTMLStream & XHTMLStream::operator<<(html::EndTag const & etag)
353 if (etag.tag_.empty())
356 // make sure there are tags to be closed
357 if (tag_stack_.empty()) {
358 writeError("Tried to close `" + etag.tag_
359 + "' when no tags were open!");
363 // first make sure we're not closing an empty tag
364 if (!pending_tags_.empty()) {
365 html::StartTag const & stag = pending_tags_.back();
366 if (etag.tag_ == stag.tag_) {
367 // we have <tag></tag>, so we discard it and remove it
368 // from the pending_tags_.
369 pending_tags_.pop_back();
372 // there is a pending tag that isn't the one we are trying
374 // is this tag itself pending?
375 // non-const iterators because we may call erase().
376 TagStack::iterator dit = pending_tags_.begin();
377 TagStack::iterator const den = pending_tags_.end();
378 for (; dit != den; ++dit) {
379 if (dit->tag_ == etag.tag_) {
380 // it was pending, so we just erase it
381 writeError("Tried to close pending tag `" + etag.tag_
382 + "' when other tags were pending. Last pending tag is `"
383 + pending_tags_.back().tag_ + "'. Tag discarded.");
384 pending_tags_.erase(dit);
388 // so etag isn't itself pending. is it even open?
389 if (!isTagOpen(etag.tag_)) {
390 writeError("Tried to close `" + etag.tag_
391 + "' when tag was not open. Tag discarded.");
394 // ok, so etag is open.
395 // our strategy will be as below: we will do what we need to
396 // do to close this tag.
397 string estr = "Closing tag `" + etag.tag_
398 + "' when other tags are pending. Discarded pending tags:\n";
399 for (dit = pending_tags_.begin(); dit != den; ++dit)
400 estr += dit->tag_ + "\n";
402 // clear the pending tags...
403 pending_tags_.clear();
404 // ...and then just fall through.
407 // is the tag we are closing the last one we opened?
408 if (etag.tag_ == tag_stack_.back().tag_) {
410 os_ << etag.asEndTag();
411 // ...and forget about it
412 tag_stack_.pop_back();
416 // we are trying to close a tag other than the one last opened.
417 // let's first see if this particular tag is still open somehow.
418 if (!isTagOpen(etag.tag_)) {
419 writeError("Tried to close `" + etag.tag_
420 + "' when tag was not open. Tag discarded.");
424 // so the tag was opened, but other tags have been opened since
425 // and not yet closed.
426 // if it's a font tag, though...
427 if (html::isFontTag(etag.tag_)) {
428 // it won't be a problem if the other tags open since this one
429 // are also font tags.
430 TagStack::const_reverse_iterator rit = tag_stack_.rbegin();
431 TagStack::const_reverse_iterator ren = tag_stack_.rend();
432 for (; rit != ren; ++rit) {
433 if (rit->tag_ == etag.tag_)
435 if (!html::isFontTag(rit->tag_)) {
436 // we'll just leave it and, presumably, have to close it later.
437 writeError("Unable to close font tag `" + etag.tag_
438 + "' due to open non-font tag `" + rit->tag_ + "'.");
444 // <em>this is <strong>bold
445 // and are being asked to closed em. we want:
446 // <em>this is <strong>bold</strong></em><strong>
447 // first, we close the intervening tags...
448 html::StartTag curtag = tag_stack_.back();
449 // ...remembering them in a stack.
451 while (curtag.tag_ != etag.tag_) {
452 os_ << curtag.asEndTag();
453 fontstack.push_back(curtag);
454 tag_stack_.pop_back();
455 curtag = tag_stack_.back();
457 // now close our tag...
458 os_ << etag.asEndTag();
459 tag_stack_.pop_back();
461 // ...and restore the other tags.
462 rit = fontstack.rbegin();
463 ren = fontstack.rend();
464 for (; rit != ren; ++rit)
465 pending_tags_.push_back(*rit);
469 // it wasn't a font tag.
470 // so other tags were opened before this one and not properly closed.
471 // so we'll close them, too. that may cause other issues later, but it
472 // at least guarantees proper nesting.
473 writeError("Closing tag `" + etag.tag_
474 + "' when other tags are open, namely:");
475 html::StartTag curtag = tag_stack_.back();
476 while (curtag.tag_ != etag.tag_) {
477 writeError(curtag.tag_);
478 os_ << curtag.asEndTag();
479 tag_stack_.pop_back();
480 curtag = tag_stack_.back();
482 // curtag is now the one we actually want.
483 os_ << curtag.asEndTag();
484 tag_stack_.pop_back();
489 // End code for XHTMLStream
493 // convenience functions
495 inline void openTag(XHTMLStream & xs, Layout const & lay)
497 xs << html::StartTag(lay.htmltag(), lay.htmlattr());
501 void openTag(XHTMLStream & xs, Layout const & lay,
502 ParagraphParameters const & params)
504 // FIXME Are there other things we should handle here?
505 string const align = alignmentToCSS(params.align());
510 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
511 xs << html::StartTag(lay.htmltag(), attrs);
515 inline void closeTag(XHTMLStream & xs, Layout const & lay)
517 xs << html::EndTag(lay.htmltag());
521 inline void openLabelTag(XHTMLStream & xs, Layout const & lay)
523 xs << html::StartTag(lay.htmllabeltag(), lay.htmllabelattr());
527 inline void closeLabelTag(XHTMLStream & xs, Layout const & lay)
529 xs << html::EndTag(lay.htmllabeltag());
533 inline void openItemTag(XHTMLStream & xs, Layout const & lay)
535 xs << html::StartTag(lay.htmlitemtag(), lay.htmlitemattr(), true);
539 void openItemTag(XHTMLStream & xs, Layout const & lay,
540 ParagraphParameters const & params)
542 // FIXME Are there other things we should handle here?
543 string const align = alignmentToCSS(params.align());
545 openItemTag(xs, lay);
548 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
549 xs << html::StartTag(lay.htmlitemtag(), attrs);
553 inline void closeItemTag(XHTMLStream & xs, Layout const & lay)
555 xs << html::EndTag(lay.htmlitemtag());
558 // end of convenience functions
560 ParagraphList::const_iterator searchParagraphHtml(
561 ParagraphList::const_iterator p,
562 ParagraphList::const_iterator const & pend)
564 for (++p; p != pend && p->layout().latextype == LATEX_PARAGRAPH; ++p)
571 ParagraphList::const_iterator searchEnvironmentHtml(
572 ParagraphList::const_iterator const pstart,
573 ParagraphList::const_iterator const & pend)
575 ParagraphList::const_iterator p = pstart;
576 Layout const & bstyle = p->layout();
577 size_t const depth = p->params().depth();
578 for (++p; p != pend; ++p) {
579 Layout const & style = p->layout();
580 // It shouldn't happen that e.g. a section command occurs inside
581 // a quotation environment, at a higher depth, but as of 6/2009,
582 // it can happen. We pretend that it's just at lowest depth.
583 if (style.latextype == LATEX_COMMAND)
585 // If depth is down, we're done
586 if (p->params().depth() < depth)
588 // If depth is up, we're not done
589 if (p->params().depth() > depth)
591 // Now we know we are at the same depth
592 if (style.latextype == LATEX_PARAGRAPH
593 || style.latexname() != bstyle.latexname())
600 ParagraphList::const_iterator makeParagraphs(Buffer const & buf,
602 OutputParams const & runparams,
604 ParagraphList::const_iterator const & pbegin,
605 ParagraphList::const_iterator const & pend)
607 ParagraphList::const_iterator const begin = text.paragraphs().begin();
608 ParagraphList::const_iterator par = pbegin;
609 for (; par != pend; ++par) {
610 Layout const & lay = par->layout();
611 if (!lay.counter.empty())
612 buf.params().documentClass().counters().step(lay.counter, OutputUpdate);
613 // FIXME We should see if there's a label to be output and
614 // do something with it.
618 // If we are already in a paragraph, and this is the first one, then we
619 // do not want to open the paragraph tag.
620 // we also do not want to open it if the current layout does not permit
621 // multiple paragraphs.
622 bool const opened = runparams.html_make_pars &&
623 (par != pbegin || !runparams.html_in_par);
625 openTag(xs, lay, par->params());
626 docstring const deferred =
627 par->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, par)));
629 // We want to issue the closing tag if either:
630 // (i) We opened it, and either html_in_par is false,
631 // or we're not in the last paragraph, anyway.
632 // (ii) We didn't open it and html_in_par is true,
633 // but we are in the first par, and there is a next par.
634 ParagraphList::const_iterator nextpar = par;
636 bool const needclose =
637 (opened && (!runparams.html_in_par || nextpar != pend))
638 || (!opened && runparams.html_in_par && par == pbegin && nextpar != pend);
643 if (!deferred.empty()) {
644 xs << XHTMLStream::ESCAPE_NONE << deferred << html::CR();
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 << pbegin->layout().labelstring(false)
662 << html::EndTag("h2")
664 << 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: