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 "OutputParams.h"
21 #include "Paragraph.h"
23 #include "TextClass.h"
25 #include "support/convert.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::escapeString(attr_, XMLStream::ESCAPE_NONE);
112 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
113 [](int c) {return !std::isspace(c);}));
114 if (!attributes.empty()) {
115 output += ' ' + attributes;
123 docstring StartTag::writeEndTag() const
125 return from_utf8("</") + tag_ + from_utf8(">");
129 bool StartTag::operator==(FontTag const &rhs) const
135 docstring EndTag::writeEndTag() const
137 return from_utf8("</") + tag_ + from_utf8(">");
141 docstring CompTag::writeTag() const
143 docstring output = '<' + from_utf8(tag_);
144 if (!attr_.empty()) {
145 // Erase the beginning of the attributes if it contains space characters: this function deals with that
147 docstring attributes = escapeString(from_utf8(attr_), XMLStream::ESCAPE_NONE);
148 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
149 [](int c) {return !std::isspace(c);}));
150 if (!attributes.empty()) {
151 output += ' ' + attributes;
159 bool FontTag::operator==(StartTag const & tag) const
161 FontTag const * const ftag = tag.asFontTag();
164 return (font_type_ == ftag->font_type_);
170 void XMLStream::writeError(std::string const &s)
173 *this << ESCAPE_NONE << from_utf8("<!-- Output Error: " + s + " -->");
178 void XMLStream::writeError(docstring const &s)
181 *this << ESCAPE_NONE << from_utf8("<!-- Output Error: ");
183 *this << ESCAPE_NONE << from_utf8(" -->");
188 bool XMLStream::closeFontTags()
190 if (isTagPending(xml::parsep_tag))
191 // we haven't had any content
194 // this may be a useless check, since we ought at least to have
195 // the parsep_tag. but it can't hurt too much to be careful.
196 if (tag_stack_.empty())
199 // first, we close any open font tags we can close
200 TagPtr *curtag = &tag_stack_.back();
201 while ((*curtag)->asFontTag()) {
202 if (**curtag != xml::parsep_tag)
203 os_ << (*curtag)->writeEndTag();
204 tag_stack_.pop_back();
205 // this shouldn't happen, since then the font tags
206 // weren't in any other tag.
207 LASSERT(!tag_stack_.empty(), return true);
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 pending_tags_.erase(dit);
484 // so etag isn't itself pending. is it even open?
485 if (!isTagOpen(etag)) {
486 writeError("Tried to close `" + to_utf8(etag.tag_)
487 + "' when tag was not open. Tag discarded.");
490 // ok, so etag is open.
491 // our strategy will be as below: we will do what we need to
492 // do to close this tag.
493 string estr = "Closing tag `" + to_utf8(etag.tag_)
494 + "' when other tags are pending. Discarded pending tags:\n";
495 for (dit = pending_tags_.begin(); dit != den; ++dit)
496 estr += to_utf8(xml::escapeString((*dit)->writeTag(), XMLStream::ESCAPE_ALL)) + "\n";
498 // clear the pending tags...
499 pending_tags_.clear();
500 // ...and then just fall through.
503 // make sure there are tags to be closed
504 if (tag_stack_.empty()) {
505 writeError("Tried to close `" + etag.tag_
506 + "' when no tags were open!");
510 // is the tag we are closing the last one we opened?
511 if (etag == *tag_stack_.back()) {
513 os_ << etag.writeEndTag();
514 // ...and forget about it
515 tag_stack_.pop_back();
519 // we are trying to close a tag other than the one last opened.
520 // let's first see if this particular tag is still open somehow.
521 if (!isTagOpen(etag)) {
522 writeError("Tried to close `" + etag.tag_
523 + "' when tag was not open. Tag discarded.");
527 // so the tag was opened, but other tags have been opened since
528 // and not yet closed.
529 // if it's a font tag, though...
530 if (etag.asFontTag()) {
531 // it won't be a problem if the other tags open since this one
532 // are also font tags.
533 TagDeque::const_reverse_iterator rit = tag_stack_.rbegin();
534 TagDeque::const_reverse_iterator ren = tag_stack_.rend();
535 for (; rit != ren; ++rit) {
538 if (!(*rit)->asFontTag()) {
539 // we'll just leave it and, presumably, have to close it later.
540 writeError("Unable to close font tag `" + etag.tag_
541 + "' due to open non-font tag `" + (*rit)->tag_ + "'.");
547 // <em>this is <strong>bold
548 // and are being asked to closed em. we want:
549 // <em>this is <strong>bold</strong></em><strong>
550 // first, we close the intervening tags...
551 TagPtr *curtag = &tag_stack_.back();
552 // ...remembering them in a stack.
554 while (etag != **curtag) {
555 os_ << (*curtag)->writeEndTag();
556 fontstack.push_back(*curtag);
557 tag_stack_.pop_back();
558 curtag = &tag_stack_.back();
560 os_ << etag.writeEndTag();
561 tag_stack_.pop_back();
563 // ...and restore the other tags.
564 rit = fontstack.rbegin();
565 ren = fontstack.rend();
566 for (; rit != ren; ++rit)
567 pending_tags_.push_back(*rit);
571 // it wasn't a font tag.
572 // so other tags were opened before this one and not properly closed.
573 // so we'll close them, too. that may cause other issues later, but it
574 // at least guarantees proper nesting.
575 writeError("Closing tag `" + etag.tag_
576 + "' when other tags are open, namely:");
577 TagPtr *curtag = &tag_stack_.back();
578 while (etag != **curtag) {
579 writeError((*curtag)->tag_);
580 if (**curtag != xml::parsep_tag)
581 os_ << (*curtag)->writeEndTag();
582 tag_stack_.pop_back();
583 curtag = &tag_stack_.back();
585 // curtag is now the one we actually want.
586 os_ << (*curtag)->writeEndTag();
587 tag_stack_.pop_back();
593 docstring xml::uniqueID(docstring const & label)
596 static atomic_uint seed(1000);
597 return label + convert<docstring>(++seed);
601 docstring xml::cleanID(docstring const & orig)
603 // The standard xml:id only allows letters, digits, '-' and '.' in a name.
604 // This routine replaces illegal characters by '-' or '.' and adds a number for uniqueness if need be.
606 // Use a cache of already mangled names: the alterations may merge several IDs as one. This ensures that the IDs
607 // are not mixed up in the document.
608 // This code could be improved: it uses Qt outside the GUI part. Any TLS implementation could do the trick.
609 typedef map<docstring, docstring> MangledMap;
610 static QThreadStorage<MangledMap> tMangledNames;
611 static QThreadStorage<int> tMangleID;
613 // If the name is already known, just return it.
614 MangledMap & mangledNames = tMangledNames.localData();
615 auto const known = mangledNames.find(orig);
616 if (known != mangledNames.end())
617 return known->second;
619 // Start creating the mangled name by iterating over the characters.
621 auto it = orig.cbegin();
622 auto end = orig.cend();
624 // Make sure it starts with a letter.
625 if (!isAlphaASCII(*it))
628 // Parse the ID character by character and change what needs to.
629 bool mangle = false; // Indicates whether the ID had to be changed, i.e. if ID no more ensured to be unique.
630 for (; it != end; ++it) {
632 if (isAlphaASCII(c) || isDigitASCII(c) || c == '-' || c == '.' || c == '_') {
634 } else if (c == ':' || c == ',' || c == ';' || c == '!') {
637 } else { // Other invalid characters, such as ' '.
643 // If there had to be a change, check if ID unicity is still guaranteed.
644 // This avoids having a clash if satisfying XML requirements for ID makes two IDs identical, like "a:b" and "a!b",
645 // as both of them would be transformed as "a.b". With this procedure, one will become "a.b" and the other "a.b-1".
646 if (mangle && mangledNames.find(content) != mangledNames.end()) {
647 int & mangleID = tMangleID.localData();
648 content += "-" + convert<docstring>(mangleID);
652 // Save the new ID to avoid recomputing it afterwards and to ensure stability over the document.
653 mangledNames[orig] = content;
658 void xml::openTag(odocstream & os, string const & name, string const & attribute)
661 // This should be fixed in layout files later.
662 string param = subst(attribute, "<", "\"");
663 param = subst(param, ">", "\"");
665 // Note: we ignore the name if it empty or if it is a comment "<!-- -->" or
666 // if the name is *dummy*.
667 // We ignore dummy because dummy is not a valid docbook element and it is
668 // the internal name given to single paragraphs in the latex output.
669 // This allow us to simplify the code a lot and is a reasonable compromise.
670 if (!name.empty() && name != "!-- --" && name != "dummy") {
671 os << '<' << from_ascii(name);
673 os << ' ' << from_ascii(param);
679 void xml::closeTag(odocstream & os, string const & name)
681 if (!name.empty() && name != "!-- --" && name != "dummy")
682 os << "</" << from_ascii(name) << '>';
686 void xml::openTag(Buffer const & buf, odocstream & os,
687 OutputParams const & runparams, Paragraph const & par)
689 Layout const & style = par.layout();
690 string const & name = style.latexname();
691 string param = style.latexparam();
692 Counters & counters = buf.params().documentClass().counters();
694 string id = par.getID(buf, runparams);
698 if (param.find('#') != string::npos) {
699 string::size_type pos = param.find("id=<");
700 string::size_type end = param.find(">");
701 if( pos != string::npos && end != string::npos)
702 param.erase(pos, end-pos + 1);
704 attribute = id + ' ' + param;
706 if (param.find('#') != string::npos) {
708 if (!style.counter.empty())
709 // This uses InternalUpdate at the moment becuase xml output
710 // does not do anything with tracked counters, and it would need
711 // to track layouts if it did want to use them.
712 counters.step(style.counter, InternalUpdate);
714 counters.step(from_ascii(name), InternalUpdate);
715 int i = counters.value(from_ascii(name));
716 attribute = subst(param, "#", convert<string>(i));
721 openTag(os, name, attribute);
725 void xml::closeTag(odocstream & os, Paragraph const & par)
727 Layout const & style = par.layout();
728 closeTag(os, style.latexname());