3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
17 #include "BufferParams.h"
20 #include "Paragraph.h"
22 #include "TextClass.h"
24 #include "support/convert.h"
25 #include "support/debug.h"
26 #include "support/docstream.h"
27 #include "support/lassert.h"
28 #include "support/lstrings.h"
29 #include "support/textutils.h"
34 #include <QThreadStorage>
37 using namespace lyx::support;
43 docstring escapeChar(char_type c, XMLStream::EscapeSettings e)
46 switch (e) { // For HTML: always ESCAPE_NONE. For XML: it depends, hence the parameter.
47 case XMLStream::ESCAPE_NONE:
48 case XMLStream::ESCAPE_COMMENTS:
51 case XMLStream::ESCAPE_ALL:
55 } else if (c == '>') {
60 case XMLStream::ESCAPE_AND:
71 docstring escapeChar(char c, XMLStream::EscapeSettings e)
73 LATTEST(static_cast<unsigned char>(c) < 0x80);
74 return escapeChar(static_cast<char_type>(c), e);
78 docstring escapeString(docstring const & raw, XMLStream::EscapeSettings e)
81 bin.reserve(raw.size() * 2); // crude approximation is sufficient
82 for (size_t i = 0; i != raw.size(); ++i) {
84 if (e == XMLStream::ESCAPE_COMMENTS && c == '-' && i > 0 && raw[i - 1] == '-')
87 bin += xml::escapeChar(c, e);
94 docstring cleanAttr(docstring const & str)
97 docstring::const_iterator it = str.begin();
98 docstring::const_iterator en = str.end();
99 for (; it != en; ++it) {
100 char_type const c = *it;
101 newname += isAlnumASCII(c) ? c : char_type('_');
107 docstring StartTag::writeTag() const
109 docstring output = '<' + tag_;
110 if (!attr_.empty()) {
111 docstring attributes = xml::trimLeft(xml::escapeString(attr_, XMLStream::ESCAPE_NONE));
112 if (!attributes.empty())
113 output += ' ' + attributes;
120 docstring StartTag::writeEndTag() const
122 return from_utf8("</") + tag_ + from_utf8(">");
126 bool StartTag::operator==(FontTag const &rhs) const
132 docstring EndTag::writeEndTag() const
134 return from_utf8("</") + tag_ + from_utf8(">");
138 docstring CompTag::writeTag() const
140 docstring output = '<' + tag_;
141 if (!attr_.empty()) {
142 // Erase the beginning of the attributes if it contains space characters: this function deals with that
144 docstring attributes = escapeString(attr_, XMLStream::ESCAPE_NONE);
145 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
146 [](char_type c) {return !isSpace(c);}));
147 if (!attributes.empty()) {
148 output += ' ' + attributes;
156 bool FontTag::operator==(StartTag const & tag) const
158 FontTag const * const ftag = tag.asFontTag();
161 return (font_type_ == ftag->font_type_);
167 void XMLStream::writeError(std::string const &s)
169 LYXERR(Debug::OUTFILE, s);
170 *this << ESCAPE_NONE << from_utf8("<!-- Output Error: " + s + " -->");
175 void XMLStream::writeError(docstring const &s)
177 LYXERR(Debug::OUTFILE, s);
178 *this << ESCAPE_NONE << from_utf8("<!-- Output Error: ");
180 *this << ESCAPE_NONE << from_utf8(" -->");
185 XMLStream::TagPtr XMLStream::getLastStackTag()
187 return tag_stack_.back();
191 bool XMLStream::closeFontTags()
193 if (isTagPending(xml::parsep_tag))
194 // we haven't had any content
197 // this may be a useless check, since we ought at least to have
198 // the parsep_tag. but it can't hurt too much to be careful.
199 if (tag_stack_.empty())
202 // first, we close any open font tags we can close
203 TagPtr *curtag = &tag_stack_.back();
204 while ((*curtag)->asFontTag()) {
205 if (**curtag != xml::parsep_tag)
206 os_ << (*curtag)->writeEndTag();
207 tag_stack_.pop_back();
208 if (tag_stack_.empty())
210 curtag = &tag_stack_.back();
213 if (**curtag == xml::parsep_tag)
216 // so we've hit a non-font tag.
217 writeError("Tags still open in closeFontTags(). Probably not a problem,\n"
218 "but you might want to check these tags:");
219 TagDeque::const_reverse_iterator it = tag_stack_.rbegin();
220 TagDeque::const_reverse_iterator const en = tag_stack_.rend();
221 for (; it != en; ++it) {
222 if (**it == xml::parsep_tag)
224 writeError((*it)->tag_);
230 void XMLStream::startDivision(bool keep_empty)
232 pending_tags_.push_back(makeTagPtr(xml::StartTag(xml::parsep_tag)));
238 void XMLStream::endDivision()
240 if (isTagPending(xml::parsep_tag)) {
241 // this case is normal. it just means we didn't have content,
242 // so the parsep_tag never got moved onto the tag stack.
243 while (!pending_tags_.empty()) {
244 // clear all pending tags up to and including the parsep tag.
245 // note that we work from the back, because we want to get rid
246 // of everything that hasn't been used.
247 TagPtr const cur_tag = pending_tags_.back();
248 pending_tags_.pop_back();
249 if (*cur_tag == xml::parsep_tag)
254 dumpTagStack("EndDivision");
260 if (!isTagOpen(xml::parsep_tag)) {
261 writeError("No division separation tag found in endDivision().");
265 // this case is also normal, if the parsep tag is the last one
266 // on the stack. otherwise, it's an error.
267 while (!tag_stack_.empty()) {
268 TagPtr const cur_tag = tag_stack_.back();
269 tag_stack_.pop_back();
270 if (*cur_tag == xml::parsep_tag)
272 writeError("Tag `" + cur_tag->tag_ + "' still open at end of paragraph. Closing.");
273 os_ << cur_tag->writeEndTag();
277 dumpTagStack("EndDivision");
282 void XMLStream::clearTagDeque()
284 while (!pending_tags_.empty()) {
285 TagPtr const & tag = pending_tags_.front();
286 if (*tag != xml::parsep_tag)
288 os_ << tag->writeTag();
289 tag_stack_.push_back(tag);
290 pending_tags_.pop_front();
295 XMLStream &XMLStream::operator<<(docstring const &d)
297 is_last_tag_cr_ = false;
299 os_ << xml::escapeString(d, escape_);
300 escape_ = ESCAPE_ALL;
305 XMLStream &XMLStream::operator<<(const char *s)
307 is_last_tag_cr_ = false;
309 docstring const d = from_ascii(s);
310 os_ << xml::escapeString(d, escape_);
311 escape_ = ESCAPE_ALL;
316 XMLStream &XMLStream::operator<<(char_type c)
318 is_last_tag_cr_ = false;
320 os_ << xml::escapeChar(c, escape_);
321 escape_ = ESCAPE_ALL;
326 XMLStream &XMLStream::operator<<(char c)
328 is_last_tag_cr_ = false;
330 os_ << xml::escapeChar(c, escape_);
331 escape_ = ESCAPE_ALL;
336 XMLStream &XMLStream::operator<<(int i)
338 is_last_tag_cr_ = false;
341 escape_ = ESCAPE_ALL;
346 XMLStream &XMLStream::operator<<(EscapeSettings e)
348 // Don't update is_last_tag_cr_ here, as this does not output anything.
354 XMLStream &XMLStream::operator<<(xml::StartTag const &tag)
356 is_last_tag_cr_ = false;
357 if (tag.tag_.empty())
359 pending_tags_.push_back(makeTagPtr(tag));
366 XMLStream &XMLStream::operator<<(xml::ParTag const &tag)
368 is_last_tag_cr_ = false;
369 if (tag.tag_.empty())
371 pending_tags_.push_back(makeTagPtr(tag));
376 XMLStream &XMLStream::operator<<(xml::CompTag const &tag)
378 is_last_tag_cr_ = false;
379 if (tag.tag_.empty())
382 os_ << tag.writeTag();
387 XMLStream &XMLStream::operator<<(xml::FontTag const &tag)
389 is_last_tag_cr_ = false;
390 if (tag.tag_.empty())
392 pending_tags_.push_back(makeTagPtr(tag));
397 XMLStream &XMLStream::operator<<(xml::CR const &)
399 is_last_tag_cr_ = true;
401 os_ << from_ascii("\n");
406 bool XMLStream::isTagOpen(xml::StartTag const &stag, int maxdepth) const
408 auto sit = tag_stack_.begin();
409 auto sen = tag_stack_.cend();
410 for (; sit != sen && maxdepth != 0; ++sit) {
419 bool XMLStream::isTagOpen(xml::EndTag const &etag, int maxdepth) const
421 auto sit = tag_stack_.begin();
422 auto sen = tag_stack_.cend();
423 for (; sit != sen && maxdepth != 0; ++sit) {
432 bool XMLStream::isTagPending(xml::StartTag const &stag, int maxdepth) const
434 auto sit = pending_tags_.begin();
435 auto sen = pending_tags_.cend();
436 for (; sit != sen && maxdepth != 0; ++sit) {
445 // this is complicated, because we want to make sure that
446 // everything is properly nested. the code ought to make
447 // sure of that, but we won't assert (yet) if we run into
448 // a problem. we'll just output error messages and try our
449 // best to make things work.
450 XMLStream &XMLStream::operator<<(xml::EndTag const &etag)
452 is_last_tag_cr_ = false;
454 if (etag.tag_.empty())
457 // if this tag is pending, we can simply discard it.
458 if (!pending_tags_.empty()) {
459 if (etag == *pending_tags_.back()) {
460 // we have <tag></tag>, so we discard it and remove it
461 // from the pending_tags_.
462 pending_tags_.pop_back();
466 // there is a pending tag that isn't the one we are trying
469 // is this tag itself pending?
470 // non-const iterators because we may call erase().
471 TagDeque::iterator dit = pending_tags_.begin();
472 TagDeque::iterator const den = pending_tags_.end();
473 for (; dit != den; ++dit) {
475 // it was pending, so we just erase it
476 writeError("Tried to close pending tag `" + to_utf8(etag.tag_)
477 + "' when other tags were pending. Last pending tag is `"
478 + to_utf8(pending_tags_.back()->writeTag())
479 + "'. Tag discarded.");
480 if (!pending_tags_.empty())
481 pending_tags_.erase(dit);
485 // so etag isn't itself pending. is it even open?
486 if (!isTagOpen(etag)) {
487 writeError("Tried to close `" + to_utf8(etag.tag_)
488 + "' when tag was not open. Tag discarded.");
491 // ok, so etag is open.
492 // our strategy will be as below: we will do what we need to
493 // do to close this tag.
494 string estr = "Closing tag `" + to_utf8(etag.tag_)
495 + "' when other tags are pending. Discarded pending tags:\n";
496 for (dit = pending_tags_.begin(); dit != den; ++dit)
497 estr += to_utf8(xml::escapeString((*dit)->writeTag(), XMLStream::ESCAPE_ALL)) + "\n";
499 // clear the pending tags...
500 pending_tags_.clear();
501 // ...and then just fall through.
504 // make sure there are tags to be closed
505 if (tag_stack_.empty()) {
506 writeError("Tried to close `" + etag.tag_
507 + "' when no tags were open!");
511 // is the tag we are closing the last one we opened?
512 if (etag == *tag_stack_.back()) {
514 os_ << etag.writeEndTag();
515 // ...and forget about it
516 tag_stack_.pop_back();
520 // we are trying to close a tag other than the one last opened.
521 // let's first see if this particular tag is still open somehow.
522 if (!isTagOpen(etag)) {
523 writeError("Tried to close `" + etag.tag_
524 + "' when tag was not open. Tag discarded.");
528 // so the tag was opened, but other tags have been opened since
529 // and not yet closed.
530 // if it's a font tag, though...
531 if (etag.asFontTag()) {
532 // it won't be a problem if the other tags open since this one
533 // are also font tags.
534 TagDeque::const_reverse_iterator rit = tag_stack_.rbegin();
535 TagDeque::const_reverse_iterator ren = tag_stack_.rend();
536 for (; rit != ren; ++rit) {
539 if (!(*rit)->asFontTag()) {
540 // we'll just leave it and, presumably, have to close it later.
541 writeError("Unable to close font tag `" + etag.tag_
542 + "' due to open non-font tag `" + (*rit)->tag_ + "'.");
548 // <em>this is <strong>bold
549 // and are being asked to closed em. we want:
550 // <em>this is <strong>bold</strong></em><strong>
551 // first, we close the intervening tags...
552 TagPtr *curtag = &tag_stack_.back();
553 // ...remembering them in a stack.
555 while (etag != **curtag) {
556 os_ << (*curtag)->writeEndTag();
557 fontstack.push_back(*curtag);
558 tag_stack_.pop_back();
559 curtag = &tag_stack_.back();
561 os_ << etag.writeEndTag();
562 tag_stack_.pop_back();
564 // ...and restore the other tags.
565 rit = fontstack.rbegin();
566 ren = fontstack.rend();
567 for (; rit != ren; ++rit)
568 pending_tags_.push_back(*rit);
572 // it wasn't a font tag.
573 // so other tags were opened before this one and not properly closed.
574 // so we'll close them, too. that may cause other issues later, but it
575 // at least guarantees proper nesting.
576 writeError("Closing tag `" + etag.tag_
577 + "' when other tags are open, namely:");
578 TagPtr *curtag = &tag_stack_.back();
579 while (etag != **curtag) {
580 writeError((*curtag)->tag_);
581 if (**curtag != xml::parsep_tag)
582 os_ << (*curtag)->writeEndTag();
583 tag_stack_.pop_back();
584 curtag = &tag_stack_.back();
586 // curtag is now the one we actually want.
587 os_ << (*curtag)->writeEndTag();
588 tag_stack_.pop_back();
594 docstring xml::uniqueID(docstring const & label)
597 static atomic_uint seed(1000);
598 return label + convert<docstring>(++seed);
602 bool xml::isNotOnlySpace(docstring const & str)
604 for (auto const & c: str) {
605 if (c != ' ' && c != '\t' && c != '\n' && c != '\v' && c != '\f' && c != '\r')
612 docstring xml::trimLeft(docstring const & str)
615 for (auto const & c: str) {
616 if (c != ' ' && c != '\t' && c != '\n' && c != '\v' && c != '\f' && c != '\r')
617 return str.substr(i, docstring::npos);
624 docstring xml::cleanID(docstring const & orig)
626 // The standard xml:id only allows letters, digits, '-' and '.' in a name.
627 // This routine replaces illegal characters by '-' or '.' and adds a number for uniqueness if need be.
629 // Use a cache of already mangled names: the alterations may merge several IDs as one. This ensures that the IDs
630 // are not mixed up in the document.
631 // This code could be improved: it uses Qt outside the GUI part. Any TLS implementation could do the trick.
632 typedef map<docstring, docstring> MangledMap;
633 static QThreadStorage<MangledMap> tMangledNames;
634 static QThreadStorage<int> tMangleID;
636 // If the name is already known, just return it.
637 MangledMap & mangledNames = tMangledNames.localData();
638 auto const known = mangledNames.find(orig);
639 if (known != mangledNames.end())
640 return known->second;
642 // Start creating the mangled name by iterating over the characters.
644 auto it = orig.cbegin();
645 auto end = orig.cend();
647 // Make sure it starts with a letter.
648 if (!isAlphaASCII(*it))
651 // Parse the ID character by character and change what needs to.
652 bool mangle = false; // Indicates whether the ID had to be changed, i.e. if ID no more ensured to be unique.
653 for (; it != end; ++it) {
655 if (isAlphaASCII(c) || isDigitASCII(c) || c == '-' || c == '.' || c == '_') {
657 } else if (c == ':' || c == ',' || c == ';' || c == '!') {
660 } else { // Other invalid characters, such as ' '.
666 // If there had to be a change, check if ID unicity is still guaranteed.
667 // This avoids having a clash if satisfying XML requirements for ID makes two IDs identical, like "a:b" and "a!b",
668 // as both of them would be transformed as "a.b". With this procedure, one will become "a.b" and the other "a.b-1".
669 if (mangle && mangledNames.find(content) != mangledNames.end()) {
670 int & mangleID = tMangleID.localData();
672 content += "-" + convert<docstring>(mangleID);
676 // Save the new ID to avoid recomputing it afterwards and to ensure stability over the document.
677 mangledNames[orig] = content;
682 void xml::openTag(odocstream & os, string const & name, string const & attribute)
685 // This should be fixed in layout files later.
686 string param = subst(attribute, "<", "\"");
687 param = subst(param, ">", "\"");
689 // Note: we ignore the name if it is empty or if it is a comment "<!-- -->" or
690 // if the name is *dummy*.
691 // We ignore dummy because dummy is not a valid DocBook element and it is
692 // the internal name given to single paragraphs in the latex output.
693 // This allow us to simplify the code a lot and is a reasonable compromise.
694 if (!name.empty() && name != "!-- --" && name != "dummy") {
695 os << '<' << from_ascii(name);
697 os << ' ' << from_ascii(param);
703 void xml::closeTag(odocstream & os, string const & name)
705 if (!name.empty() && name != "!-- --" && name != "dummy")
706 os << "</" << from_ascii(name) << '>';
710 void xml::openTag(Buffer const & buf, odocstream & os,
711 OutputParams const & runparams, Paragraph const & par)
713 Layout const & style = par.layout();
714 string const & name = style.latexname();
715 string param = style.latexparam();
716 Counters & counters = buf.params().documentClass().counters();
718 string id = par.getID(buf, runparams);
722 if (param.find('#') != string::npos) {
723 string::size_type pos = param.find("id=<");
724 string::size_type end = param.find(">");
725 if( pos != string::npos && end != string::npos)
726 param.erase(pos, end-pos + 1);
728 attribute = id + ' ' + param;
730 if (param.find('#') != string::npos) {
732 if (!style.counter.empty())
733 // This uses InternalUpdate at the moment becuase xml output
734 // does not do anything with tracked counters, and it would need
735 // to track layouts if it did want to use them.
736 counters.step(style.counter, InternalUpdate);
738 counters.step(from_ascii(name), InternalUpdate);
739 int i = counters.value(from_ascii(name));
740 attribute = subst(param, "#", convert<string>(i));
745 openTag(os, name, attribute);
749 void xml::closeTag(odocstream & os, Paragraph const & par)
751 Layout const & style = par.layout();
752 closeTag(os, style.latexname());
756 void openInlineTag(XMLStream & xs, const docstring & tag, const docstring & attr)
758 xs << xml::StartTag(tag, attr);
762 void closeInlineTag(XMLStream & xs, const docstring & tag)
764 xs << xml::EndTag(tag);
768 void openParTag(XMLStream & xs, const docstring & tag, const docstring & attr)
770 if (!xs.isLastTagCR())
772 xs << xml::StartTag(tag, attr);
776 void closeParTag(XMLStream & xs, const docstring & tag)
778 xs << xml::EndTag(tag);
783 void openBlockTag(XMLStream & xs, const docstring & tag, const docstring & attr)
785 if (!xs.isLastTagCR())
787 xs << xml::StartTag(tag, attr);
792 void closeBlockTag(XMLStream & xs, const docstring & tag)
794 if (!xs.isLastTagCR())
796 xs << xml::EndTag(tag);
801 void xml::openTag(XMLStream & xs, const docstring & tag, const docstring & attr, const std::string & tagtype)
803 if (tag.empty() || tag == "NONE") // Common check to be performed elsewhere, if it was not here.
806 if (tag == "para" || tagtype == "paragraph") // Special case for <para>: always considered as a paragraph.
807 openParTag(xs, tag, attr);
808 else if (tagtype == "block")
809 openBlockTag(xs, tag, attr);
810 else if (tagtype == "inline")
811 openInlineTag(xs, tag, attr);
812 else if (tagtype == "none")
813 xs << xml::StartTag(tag, attr);
815 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + to_utf8(tag) + " " + to_utf8(attr) + "'");
819 void xml::openTag(XMLStream & xs, const std::string & tag, const std::string & attr, const std::string & tagtype)
821 xml::openTag(xs, from_utf8(tag), from_utf8(attr), tagtype);
825 void xml::openTag(XMLStream & xs, const docstring & tag, const std::string & attr, const std::string & tagtype)
827 xml::openTag(xs, tag, from_utf8(attr), tagtype);
831 void xml::openTag(XMLStream & xs, const std::string & tag, const docstring & attr, const std::string & tagtype)
833 xml::openTag(xs, from_utf8(tag), attr, tagtype);
837 void xml::closeTag(XMLStream & xs, const docstring & tag, const std::string & tagtype)
839 if (tag.empty() || tag == "NONE" || tag == "IGNORE")
842 if (tag == "para" || tagtype == "paragraph") // Special case for <para>: always considered as a paragraph.
843 closeParTag(xs, tag);
844 else if (tagtype == "block")
845 closeBlockTag(xs, tag);
846 else if (tagtype == "inline")
847 closeInlineTag(xs, tag);
848 else if (tagtype == "none")
849 xs << xml::EndTag(tag);
851 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + to_utf8(tag) + "'");
855 void xml::closeTag(XMLStream & xs, const std::string & tag, const std::string & tagtype)
857 xml::closeTag(xs, from_utf8(tag), tagtype);
861 void xml::compTag(XMLStream & xs, const docstring & tag, const docstring & attr, const std::string & tagtype)
863 if (tag.empty() || tag == from_ascii("NONE"))
866 // Special case for <para>: always considered as a paragraph.
867 if (tag == from_ascii("para") || tagtype == "paragraph" || tagtype == "block") {
868 if (!xs.isLastTagCR())
870 xs << xml::CompTag(tag, attr);
872 } else if (tagtype == "inline") {
873 xs << xml::CompTag(tag, attr);
875 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + to_utf8(tag) + "'");
880 void xml::compTag(XMLStream & xs, const std::string & tag, const std::string & attr, const std::string & tagtype)
882 xml::compTag(xs, from_utf8(tag), from_utf8(attr), tagtype);
886 void xml::compTag(XMLStream & xs, const docstring & tag, const std::string & attr, const std::string & tagtype)
888 xml::compTag(xs, tag, from_utf8(attr), tagtype);
892 void xml::compTag(XMLStream & xs, const std::string & tag, const docstring & attr, const std::string & tagtype)
894 xml::compTag(xs, from_utf8(tag), attr, tagtype);