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)
149 return s == "em" || s == "strong" || s == "i" || s == "b";
153 docstring StartTag::asTag() const
155 string output = "<" + tag_;
157 output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE);
159 return from_utf8(output);
163 docstring StartTag::asEndTag() const
165 string output = "</" + tag_ + ">";
166 return from_utf8(output);
170 docstring EndTag::asEndTag() const
172 string output = "</" + tag_ + ">";
173 return from_utf8(output);
177 docstring CompTag::asTag() const
179 string output = "<" + tag_;
181 output += " " + html::htmlize(attr_, XHTMLStream::ESCAPE_NONE);
183 return from_utf8(output);
190 ////////////////////////////////////////////////////////////////
194 ////////////////////////////////////////////////////////////////
196 XHTMLStream::XHTMLStream(odocstream & os)
197 : os_(os), escape_(ESCAPE_ALL)
201 void XHTMLStream::writeError(std::string const & s)
204 os_ << from_utf8("<!-- Output Error: " + s + " -->");
209 // an illegal tag for internal use
210 static string const parsep_tag = "&LyX_parsep_tag&";
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();
231 if (curtag.tag_ == parsep_tag)
234 // so we've hit a non-font tag.
235 writeError("Tags still open in closeFontTags(). Probably not a problem,\n"
236 "but you might want to check these tags:");
237 TagStack::const_reverse_iterator it = tag_stack_.rbegin();
238 TagStack::const_reverse_iterator const en = tag_stack_.rend();
239 for (; it != en; ++it) {
240 string const tagname = it->tag_;
241 if (tagname == parsep_tag)
243 writeError(it->tag_);
249 void XHTMLStream::startParagraph()
251 pending_tags_.push_back(html::StartTag(parsep_tag));
255 void XHTMLStream::endParagraph()
257 if (!isTagOpen(parsep_tag)) {
259 TagStack::const_iterator dit = pending_tags_.begin();
260 TagStack::const_iterator const den = pending_tags_.end();
262 for (; dit != den; ++dit) {
263 if (dit->tag_ == parsep_tag) {
270 writeError("No paragraph separation tag found in endParagraph().");
274 // this case is normal.
275 while (!pending_tags_.empty()) {
276 // clear all pending tags up to and including the parsep tag.
277 // note that we work from the back, because we want to get rid
278 // of everything that hasnt' been used.
279 html::StartTag const cur_tag = pending_tags_.back();
280 string const & tag = cur_tag.tag_;
281 tag_stack_.pop_back();
282 if (tag == parsep_tag)
288 // this case is also normal, if the parsep tag is the last one
289 // on the stack. otherwise, it's an error.
290 while (!tag_stack_.empty()) {
291 html::StartTag const cur_tag = tag_stack_.back();
292 string const & tag = cur_tag.tag_;
293 tag_stack_.pop_back();
294 if (tag == parsep_tag)
296 writeError("Tag `" + tag + "' still open at end of paragraph. Closing.");
297 os_ << cur_tag.asEndTag();
302 void XHTMLStream::clearTagDeque()
304 while (!pending_tags_.empty()) {
305 html::StartTag const & tag = pending_tags_.front();
306 if (tag.tag_ != parsep_tag)
309 tag_stack_.push_back(tag);
310 pending_tags_.pop_front();
315 XHTMLStream & XHTMLStream::operator<<(docstring const & d)
318 os_ << html::htmlize(d, escape_);
319 escape_ = ESCAPE_ALL;
324 XHTMLStream & XHTMLStream::operator<<(const char * s)
327 docstring const d = from_ascii(s);
328 os_ << html::htmlize(d, escape_);
329 escape_ = ESCAPE_ALL;
334 XHTMLStream & XHTMLStream::operator<<(char_type c)
337 os_ << html::escapeChar(c, escape_);
338 escape_ = ESCAPE_ALL;
343 XHTMLStream & XHTMLStream::operator<<(char c)
346 string const d = html::escapeChar(c, escape_);
347 escape_ = ESCAPE_ALL;
352 XHTMLStream & XHTMLStream::operator<<(int i)
356 escape_ = ESCAPE_ALL;
361 XHTMLStream & XHTMLStream::operator<<(EscapeSettings e)
368 XHTMLStream & XHTMLStream::operator<<(html::StartTag const & tag)
370 if (tag.tag_.empty())
372 pending_tags_.push_back(tag);
379 XHTMLStream & XHTMLStream::operator<<(html::CompTag const & tag)
381 if (tag.tag_.empty())
391 XHTMLStream & XHTMLStream::operator<<(html::CR const &)
394 os_ << from_ascii("\n");
399 bool XHTMLStream::isTagOpen(string const & stag)
401 TagStack::const_iterator sit = tag_stack_.begin();
402 TagStack::const_iterator const sen = tag_stack_.end();
403 for (; sit != sen; ++sit)
404 if (sit->tag_ == stag)
410 // this is complicated, because we want to make sure that
411 // everything is properly nested. the code ought to make
412 // sure of that, but we won't assert (yet) if we run into
413 // a problem. we'll just output error messages and try our
414 // best to make things work.
415 XHTMLStream & XHTMLStream::operator<<(html::EndTag const & etag)
417 if (etag.tag_.empty())
420 // make sure there are tags to be closed
421 if (tag_stack_.empty()) {
422 writeError("Tried to close `" + etag.tag_
423 + "' when no tags were open!");
427 // first make sure we're not closing an empty tag
428 if (!pending_tags_.empty()) {
429 html::StartTag const & stag = pending_tags_.back();
430 if (etag.tag_ == stag.tag_) {
431 // we have <tag></tag>, so we discard it and remove it
432 // from the pending_tags_.
433 pending_tags_.pop_back();
436 // there is a pending tag that isn't the one we are trying
438 // is this tag itself pending?
439 // non-const iterators because we may call erase().
440 TagStack::iterator dit = pending_tags_.begin();
441 TagStack::iterator const den = pending_tags_.end();
442 for (; dit != den; ++dit) {
443 if (dit->tag_ == etag.tag_) {
444 // it was pending, so we just erase it
445 writeError("Tried to close pending tag `" + etag.tag_
446 + "' when other tags were pending. Last pending tag is `"
447 + pending_tags_.back().tag_ + "'. Tag discarded.");
448 pending_tags_.erase(dit);
452 // so etag isn't itself pending. is it even open?
453 if (!isTagOpen(etag.tag_)) {
454 writeError("Tried to close `" + etag.tag_
455 + "' when tag was not open. Tag discarded.");
458 // ok, so etag is open.
459 // our strategy will be as below: we will do what we need to
460 // do to close this tag.
461 string estr = "Closing tag `" + etag.tag_
462 + "' when other tags are pending. Discarded pending tags:\n";
463 for (dit = pending_tags_.begin(); dit != den; ++dit)
464 estr += dit->tag_ + "\n";
466 // clear the pending tags...
467 pending_tags_.clear();
468 // ...and then just fall through.
471 // is the tag we are closing the last one we opened?
472 if (etag.tag_ == tag_stack_.back().tag_) {
474 os_ << etag.asEndTag();
475 // ...and forget about it
476 tag_stack_.pop_back();
480 // we are trying to close a tag other than the one last opened.
481 // let's first see if this particular tag is still open somehow.
482 if (!isTagOpen(etag.tag_)) {
483 writeError("Tried to close `" + etag.tag_
484 + "' when tag was not open. Tag discarded.");
488 // so the tag was opened, but other tags have been opened since
489 // and not yet closed.
490 // if it's a font tag, though...
491 if (html::isFontTag(etag.tag_)) {
492 // it won't be a problem if the other tags open since this one
493 // are also font tags.
494 TagStack::const_reverse_iterator rit = tag_stack_.rbegin();
495 TagStack::const_reverse_iterator ren = tag_stack_.rend();
496 for (; rit != ren; ++rit) {
497 if (rit->tag_ == etag.tag_)
499 if (!html::isFontTag(rit->tag_)) {
500 // we'll just leave it and, presumably, have to close it later.
501 writeError("Unable to close font tag `" + etag.tag_
502 + "' due to open non-font tag `" + rit->tag_ + "'.");
508 // <em>this is <strong>bold
509 // and are being asked to closed em. we want:
510 // <em>this is <strong>bold</strong></em><strong>
511 // first, we close the intervening tags...
512 html::StartTag curtag = tag_stack_.back();
513 // ...remembering them in a stack.
515 while (curtag.tag_ != etag.tag_) {
516 os_ << curtag.asEndTag();
517 fontstack.push_back(curtag);
518 tag_stack_.pop_back();
519 curtag = tag_stack_.back();
521 // now close our tag...
522 os_ << etag.asEndTag();
523 tag_stack_.pop_back();
525 // ...and restore the other tags.
526 rit = fontstack.rbegin();
527 ren = fontstack.rend();
528 for (; rit != ren; ++rit)
529 pending_tags_.push_back(*rit);
533 // it wasn't a font tag.
534 // so other tags were opened before this one and not properly closed.
535 // so we'll close them, too. that may cause other issues later, but it
536 // at least guarantees proper nesting.
537 writeError("Closing tag `" + etag.tag_
538 + "' when other tags are open, namely:");
539 html::StartTag curtag = tag_stack_.back();
540 while (curtag.tag_ != etag.tag_) {
541 writeError(curtag.tag_);
542 if (curtag.tag_ != parsep_tag)
543 os_ << curtag.asEndTag();
544 tag_stack_.pop_back();
545 curtag = tag_stack_.back();
547 // curtag is now the one we actually want.
548 os_ << curtag.asEndTag();
549 tag_stack_.pop_back();
554 // End code for XHTMLStream
558 // convenience functions
560 inline void openTag(XHTMLStream & xs, Layout const & lay)
562 xs << html::StartTag(lay.htmltag(), lay.htmlattr());
566 void openTag(XHTMLStream & xs, Layout const & lay,
567 ParagraphParameters const & params)
569 // FIXME Are there other things we should handle here?
570 string const align = alignmentToCSS(params.align());
575 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
576 xs << html::StartTag(lay.htmltag(), attrs);
580 inline void closeTag(XHTMLStream & xs, Layout const & lay)
582 xs << html::EndTag(lay.htmltag());
586 inline void openLabelTag(XHTMLStream & xs, Layout const & lay)
588 xs << html::StartTag(lay.htmllabeltag(), lay.htmllabelattr());
592 inline void closeLabelTag(XHTMLStream & xs, Layout const & lay)
594 xs << html::EndTag(lay.htmllabeltag());
598 inline void openItemTag(XHTMLStream & xs, Layout const & lay)
600 xs << html::StartTag(lay.htmlitemtag(), lay.htmlitemattr(), true);
604 void openItemTag(XHTMLStream & xs, Layout const & lay,
605 ParagraphParameters const & params)
607 // FIXME Are there other things we should handle here?
608 string const align = alignmentToCSS(params.align());
610 openItemTag(xs, lay);
613 string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
614 xs << html::StartTag(lay.htmlitemtag(), attrs);
618 inline void closeItemTag(XHTMLStream & xs, Layout const & lay)
620 xs << html::EndTag(lay.htmlitemtag());
623 // end of convenience functions
625 ParagraphList::const_iterator searchParagraphHtml(
626 ParagraphList::const_iterator p,
627 ParagraphList::const_iterator const & pend)
629 for (++p; p != pend && p->layout().latextype == LATEX_PARAGRAPH; ++p)
636 ParagraphList::const_iterator searchEnvironmentHtml(
637 ParagraphList::const_iterator const pstart,
638 ParagraphList::const_iterator const & pend)
640 ParagraphList::const_iterator p = pstart;
641 Layout const & bstyle = p->layout();
642 size_t const depth = p->params().depth();
643 for (++p; p != pend; ++p) {
644 Layout const & style = p->layout();
645 // It shouldn't happen that e.g. a section command occurs inside
646 // a quotation environment, at a higher depth, but as of 6/2009,
647 // it can happen. We pretend that it's just at lowest depth.
648 if (style.latextype == LATEX_COMMAND)
650 // If depth is down, we're done
651 if (p->params().depth() < depth)
653 // If depth is up, we're not done
654 if (p->params().depth() > depth)
656 // Now we know we are at the same depth
657 if (style.latextype == LATEX_PARAGRAPH
658 || style.latexname() != bstyle.latexname())
665 ParagraphList::const_iterator makeParagraphs(Buffer const & buf,
667 OutputParams const & runparams,
669 ParagraphList::const_iterator const & pbegin,
670 ParagraphList::const_iterator const & pend)
672 ParagraphList::const_iterator const begin = text.paragraphs().begin();
673 ParagraphList::const_iterator par = pbegin;
674 for (; par != pend; ++par) {
675 Layout const & lay = par->layout();
676 if (!lay.counter.empty())
677 buf.params().documentClass().counters().step(lay.counter, OutputUpdate);
678 // FIXME We should see if there's a label to be output and
679 // do something with it.
683 // If we are already in a paragraph, and this is the first one, then we
684 // do not want to open the paragraph tag.
685 // we also do not want to open it if the current layout does not permit
686 // multiple paragraphs.
687 bool const opened = runparams.html_make_pars &&
688 (par != pbegin || !runparams.html_in_par);
690 openTag(xs, lay, par->params());
691 docstring const deferred =
692 par->simpleLyXHTMLOnePar(buf, xs, runparams, text.outerFont(distance(begin, par)));
694 // We want to issue the closing tag if either:
695 // (i) We opened it, and either html_in_par is false,
696 // or we're not in the last paragraph, anyway.
697 // (ii) We didn't open it and html_in_par is true,
698 // but we are in the first par, and there is a next par.
699 ParagraphList::const_iterator nextpar = par;
701 bool const needclose =
702 (opened && (!runparams.html_in_par || nextpar != pend))
703 || (!opened && runparams.html_in_par && par == pbegin && nextpar != pend);
708 if (!deferred.empty()) {
709 xs << XHTMLStream::ESCAPE_NONE << deferred << html::CR();
716 ParagraphList::const_iterator makeBibliography(Buffer const & buf,
718 OutputParams const & runparams,
720 ParagraphList::const_iterator const & pbegin,
721 ParagraphList::const_iterator const & pend)
724 // Use TextClass::htmlTOCLayout() to figure out how we should look.
725 xs << html::StartTag("h2", "class='bibliography'")
726 << pbegin->layout().labelstring(false)
727 << html::EndTag("h2")
729 << html::StartTag("div", "class='bibliography'")
731 makeParagraphs(buf, xs, runparams, text, pbegin, pend);
732 xs << html::EndTag("div");
737 bool isNormalEnv(Layout const & lay)
739 return lay.latextype == LATEX_ENVIRONMENT
740 || lay.latextype == LATEX_BIB_ENVIRONMENT;
744 ParagraphList::const_iterator makeEnvironmentHtml(Buffer const & buf,
746 OutputParams const & runparams,
748 ParagraphList::const_iterator const & pbegin,
749 ParagraphList::const_iterator const & pend)
751 ParagraphList::const_iterator const begin = text.paragraphs().begin();
752 ParagraphList::const_iterator par = pbegin;
753 Layout const & bstyle = par->layout();
754 depth_type const origdepth = pbegin->params().depth();
756 // open tag for this environment
760 // we will on occasion need to remember a layout from before.
761 Layout const * lastlay = 0;
763 while (par != pend) {
764 Layout const & style = par->layout();
765 // the counter only gets stepped if we're in some kind of list,
766 // or if it's the first time through.
767 // note that enum, etc, are handled automatically.
768 // FIXME There may be a bug here about user defined enumeration
769 // types. If so, then we'll need to take the counter and add "i",
770 // "ii", etc, as with enum.
771 Counters & cnts = buf.params().documentClass().counters();
772 docstring const & cntr = style.counter;
773 if (!style.counter.empty()
774 && (par == pbegin || !isNormalEnv(style))
775 && cnts.hasCounter(cntr)
777 cnts.step(cntr, OutputUpdate);
778 ParagraphList::const_iterator send;
779 // this will be positive, if we want to skip the initial word
780 // (if it's been taken for the label).
783 switch (style.latextype) {
784 case LATEX_ENVIRONMENT:
785 case LATEX_LIST_ENVIRONMENT:
786 case LATEX_ITEM_ENVIRONMENT: {
787 // There are two possiblities in this case.
788 // One is that we are still in the environment in which we
789 // started---which we will be if the depth is the same.
790 if (par->params().depth() == origdepth) {
791 LASSERT(bstyle == style, /* */);
793 closeItemTag(xs, *lastlay);
797 bool const labelfirst = style.htmllabelfirst();
799 openItemTag(xs, style, par->params());
802 if (style.labeltype != LABEL_NO_LABEL &&
803 style.htmllabeltag() != "NONE") {
804 if (isNormalEnv(style)) {
805 // in this case, we print the label only for the first
806 // paragraph (as in a theorem).
808 docstring const lbl =
809 pbegin->params().labelString();
811 openLabelTag(xs, style);
813 closeLabelTag(xs, style);
817 } else { // some kind of list
818 if (style.labeltype == LABEL_MANUAL) {
819 openLabelTag(xs, style);
820 sep = par->firstWordLyXHTML(xs, runparams);
821 closeLabelTag(xs, style);
825 openLabelTag(xs, style);
826 xs << par->params().labelString();
827 closeLabelTag(xs, style);
831 } // end label output
834 openItemTag(xs, style, par->params());
836 par->simpleLyXHTMLOnePar(buf, xs, runparams,
837 text.outerFont(distance(begin, par)), sep);
840 // We may not want to close the tag yet, in particular:
841 // If we're not at the end...
843 // and are doing items...
844 && !isNormalEnv(style)
845 // and if the depth has changed...
846 && par->params().depth() != origdepth) {
847 // then we'll save this layout for later, and close it when
848 // we get another item.
851 closeItemTag(xs, style);
854 // The other possibility is that the depth has increased, in which
855 // case we need to recurse.
857 send = searchEnvironmentHtml(par, pend);
858 par = makeEnvironmentHtml(buf, xs, runparams, text, par, send);
862 case LATEX_PARAGRAPH:
863 send = searchParagraphHtml(par, pend);
864 par = makeParagraphs(buf, xs, runparams, text, par, send);
867 case LATEX_BIB_ENVIRONMENT:
870 par = makeParagraphs(buf, xs, runparams, text, par, send);
880 closeItemTag(xs, *lastlay);
881 closeTag(xs, bstyle);
887 void makeCommand(Buffer const & buf,
889 OutputParams const & runparams,
891 ParagraphList::const_iterator const & pbegin)
893 Layout const & style = pbegin->layout();
894 if (!style.counter.empty())
895 buf.params().documentClass().counters().step(style.counter, OutputUpdate);
897 openTag(xs, style, pbegin->params());
899 // Label around sectioning number:
900 // FIXME Probably need to account for LABEL_MANUAL
901 if (style.labeltype != LABEL_NO_LABEL) {
902 openLabelTag(xs, style);
903 xs << pbegin->params().labelString();
904 closeLabelTag(xs, style);
905 // Otherwise the label might run together with the text
906 xs << from_ascii(" ");
909 ParagraphList::const_iterator const begin = text.paragraphs().begin();
910 pbegin->simpleLyXHTMLOnePar(buf, xs, runparams,
911 text.outerFont(distance(begin, pbegin)));
916 } // end anonymous namespace
919 void xhtmlParagraphs(Text const & text,
922 OutputParams const & runparams)
924 ParagraphList const & paragraphs = text.paragraphs();
925 if (runparams.par_begin == runparams.par_end) {
926 runparams.par_begin = 0;
927 runparams.par_end = paragraphs.size();
929 pit_type bpit = runparams.par_begin;
930 pit_type const epit = runparams.par_end;
931 LASSERT(bpit < epit, /* */);
933 OutputParams ourparams = runparams;
934 ParagraphList::const_iterator const pend =
935 (epit == (int) paragraphs.size()) ?
936 paragraphs.end() : paragraphs.constIterator(epit);
937 while (bpit < epit) {
938 ParagraphList::const_iterator par = paragraphs.constIterator(bpit);
939 if (par->params().startOfAppendix()) {
940 // FIXME: only the counter corresponding to toplevel
941 // sectioning should be reset
942 Counters & cnts = buf.masterBuffer()->params().documentClass().counters();
946 Layout const & style = par->layout();
947 ParagraphList::const_iterator const lastpar = par;
948 ParagraphList::const_iterator send;
950 switch (style.latextype) {
951 case LATEX_COMMAND: {
952 // The files with which we are working never have more than
953 // one paragraph in a command structure.
955 // if (ourparams.html_in_par)
956 // fix it so we don't get sections inside standard, e.g.
957 // note that we may then need to make runparams not const, so we
958 // can communicate that back.
959 // FIXME Maybe this fix should be in the routines themselves, in case
960 // they are called from elsewhere.
961 makeCommand(buf, xs, ourparams, text, par);
965 case LATEX_ENVIRONMENT:
966 case LATEX_LIST_ENVIRONMENT:
967 case LATEX_ITEM_ENVIRONMENT: {
968 // FIXME Same fix here.
969 send = searchEnvironmentHtml(par, pend);
970 par = makeEnvironmentHtml(buf, xs, ourparams, text, par, send);
973 case LATEX_BIB_ENVIRONMENT: {
974 // FIXME Same fix here.
975 send = searchEnvironmentHtml(par, pend);
976 par = makeBibliography(buf, xs, ourparams, text, par, send);
979 case LATEX_PARAGRAPH:
980 send = searchParagraphHtml(par, pend);
981 par = makeParagraphs(buf, xs, ourparams, text, par, send);
984 bpit += distance(lastpar, par);
989 string alignmentToCSS(LyXAlignment align) {
991 case LYX_ALIGN_BLOCK:
992 // we are NOT going to use text-align: justify!!
995 case LYX_ALIGN_RIGHT:
997 case LYX_ALIGN_CENTER: