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:
50 case XMLStream::ESCAPE_ALL:
54 } else if (c == '>') {
59 case XMLStream::ESCAPE_AND:
70 // escape what needs escaping
71 docstring xmlize(docstring const &str, XMLStream::EscapeSettings e) {
73 docstring::const_iterator it = str.begin();
74 docstring::const_iterator en = str.end();
75 for (; it != en; ++it)
76 d << escapeChar(*it, e);
81 docstring escapeChar(char c, XMLStream::EscapeSettings e)
83 LATTEST(static_cast<unsigned char>(c) < 0x80);
84 return escapeChar(static_cast<char_type>(c), e);
88 docstring cleanAttr(docstring const & str)
91 docstring::const_iterator it = str.begin();
92 docstring::const_iterator en = str.end();
93 for (; it != en; ++it) {
94 char_type const c = *it;
95 newname += isAlnumASCII(c) ? c : char_type('_');
101 docstring StartTag::writeTag() const
103 docstring output = '<' + tag_;
104 if (!attr_.empty()) {
105 docstring attributes = xml::xmlize(attr_, XMLStream::ESCAPE_NONE);
106 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
107 [](int c) {return !std::isspace(c);}));
108 if (!attributes.empty()) {
109 output += ' ' + attributes;
117 docstring StartTag::writeEndTag() const
119 return from_utf8("</") + tag_ + from_utf8(">");
123 bool StartTag::operator==(FontTag const &rhs) const
129 docstring EndTag::writeEndTag() const
131 return from_utf8("</") + tag_ + from_utf8(">");
135 docstring CompTag::writeTag() const
137 docstring output = '<' + from_utf8(tag_);
138 if (!attr_.empty()) {
139 // Erase the beginning of the attributes if it contains space characters: this function deals with that
141 docstring attributes = xmlize(from_utf8(attr_), XMLStream::ESCAPE_NONE);
142 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
143 [](int c) {return !std::isspace(c);}));
144 if (!attributes.empty()) {
145 output += ' ' + attributes;
153 bool FontTag::operator==(StartTag const & tag) const
155 FontTag const * const ftag = tag.asFontTag();
158 return (font_type_ == ftag->font_type_);
164 void XMLStream::writeError(std::string const &s) const
167 os_ << from_utf8("<!-- Output Error: " + s + " -->\n");
171 void XMLStream::writeError(docstring const &s) const
174 os_ << from_utf8("<!-- Output Error: ") << s << from_utf8(" -->\n");
178 bool XMLStream::closeFontTags()
180 if (isTagPending(xml::parsep_tag))
181 // we haven't had any content
184 // this may be a useless check, since we ought at least to have
185 // the parsep_tag. but it can't hurt too much to be careful.
186 if (tag_stack_.empty())
189 // first, we close any open font tags we can close
190 TagPtr *curtag = &tag_stack_.back();
191 while ((*curtag)->asFontTag()) {
192 if (**curtag != xml::parsep_tag)
193 os_ << (*curtag)->writeEndTag();
194 tag_stack_.pop_back();
195 // this shouldn't happen, since then the font tags
196 // weren't in any other tag.
197 // LASSERT(!tag_stack_.empty(), return true);
198 if (tag_stack_.empty())
200 curtag = &tag_stack_.back();
203 if (**curtag == xml::parsep_tag)
206 // so we've hit a non-font tag.
207 writeError("Tags still open in closeFontTags(). Probably not a problem,\n"
208 "but you might want to check these tags:");
209 TagDeque::const_reverse_iterator it = tag_stack_.rbegin();
210 TagDeque::const_reverse_iterator const en = tag_stack_.rend();
211 for (; it != en; ++it) {
212 if (**it == xml::parsep_tag)
214 writeError((*it)->tag_);
220 void XMLStream::startDivision(bool keep_empty)
222 pending_tags_.push_back(makeTagPtr(xml::StartTag(xml::parsep_tag)));
228 void XMLStream::endDivision()
230 if (isTagPending(xml::parsep_tag)) {
231 // this case is normal. it just means we didn't have content,
232 // so the parsep_tag never got moved onto the tag stack.
233 while (!pending_tags_.empty()) {
234 // clear all pending tags up to and including the parsep tag.
235 // note that we work from the back, because we want to get rid
236 // of everything that hasn't been used.
237 TagPtr const cur_tag = pending_tags_.back();
238 pending_tags_.pop_back();
239 if (*cur_tag == xml::parsep_tag)
244 dumpTagStack("EndDivision");
250 if (!isTagOpen(xml::parsep_tag)) {
251 writeError("No division separation tag found in endDivision().");
255 // this case is also normal, if the parsep tag is the last one
256 // on the stack. otherwise, it's an error.
257 while (!tag_stack_.empty()) {
258 TagPtr const cur_tag = tag_stack_.back();
259 tag_stack_.pop_back();
260 if (*cur_tag == xml::parsep_tag)
262 writeError("Tag `" + cur_tag->tag_ + "' still open at end of paragraph. Closing.");
263 os_ << cur_tag->writeEndTag();
267 dumpTagStack("EndDivision");
272 void XMLStream::clearTagDeque()
274 while (!pending_tags_.empty()) {
275 TagPtr const & tag = pending_tags_.front();
276 if (*tag != xml::parsep_tag)
278 os_ << tag->writeTag();
279 tag_stack_.push_back(tag);
280 pending_tags_.pop_front();
285 XMLStream &XMLStream::operator<<(docstring const &d)
288 os_ << xml::xmlize(d, escape_);
289 escape_ = ESCAPE_ALL;
294 XMLStream &XMLStream::operator<<(const char *s)
297 docstring const d = from_ascii(s);
298 os_ << xml::xmlize(d, escape_);
299 escape_ = ESCAPE_ALL;
304 XMLStream &XMLStream::operator<<(char_type c)
307 os_ << xml::escapeChar(c, escape_);
308 escape_ = ESCAPE_ALL;
313 XMLStream &XMLStream::operator<<(char c)
316 os_ << xml::escapeChar(c, escape_);
317 escape_ = ESCAPE_ALL;
322 XMLStream &XMLStream::operator<<(int i)
326 escape_ = ESCAPE_ALL;
331 XMLStream &XMLStream::operator<<(EscapeSettings e)
338 XMLStream &XMLStream::operator<<(xml::StartTag const &tag)
340 if (tag.tag_.empty())
342 pending_tags_.push_back(makeTagPtr(tag));
349 XMLStream &XMLStream::operator<<(xml::ParTag const &tag)
351 if (tag.tag_.empty())
353 pending_tags_.push_back(makeTagPtr(tag));
358 XMLStream &XMLStream::operator<<(xml::CompTag const &tag)
360 if (tag.tag_.empty())
363 os_ << tag.writeTag();
368 XMLStream &XMLStream::operator<<(xml::FontTag const &tag)
370 if (tag.tag_.empty())
372 pending_tags_.push_back(makeTagPtr(tag));
377 XMLStream &XMLStream::operator<<(xml::CR const &)
380 os_ << from_ascii("\n");
385 bool XMLStream::isTagOpen(xml::StartTag const &stag, int maxdepth) const
387 auto sit = tag_stack_.begin();
388 auto sen = tag_stack_.cend();
389 for (; sit != sen && maxdepth != 0; ++sit) {
398 bool XMLStream::isTagOpen(xml::EndTag const &etag, int maxdepth) const
400 auto sit = tag_stack_.begin();
401 auto sen = tag_stack_.cend();
402 for (; sit != sen && maxdepth != 0; ++sit) {
411 bool XMLStream::isTagPending(xml::StartTag const &stag, int maxdepth) const
413 auto sit = pending_tags_.begin();
414 auto sen = pending_tags_.cend();
415 for (; sit != sen && maxdepth != 0; ++sit) {
424 // this is complicated, because we want to make sure that
425 // everything is properly nested. the code ought to make
426 // sure of that, but we won't assert (yet) if we run into
427 // a problem. we'll just output error messages and try our
428 // best to make things work.
429 XMLStream &XMLStream::operator<<(xml::EndTag const &etag)
431 if (etag.tag_.empty())
434 // if this tag is pending, we can simply discard it.
435 if (!pending_tags_.empty()) {
436 if (etag == *pending_tags_.back()) {
437 // we have <tag></tag>, so we discard it and remove it
438 // from the pending_tags_.
439 pending_tags_.pop_back();
443 // there is a pending tag that isn't the one we are trying
446 // is this tag itself pending?
447 // non-const iterators because we may call erase().
448 TagDeque::iterator dit = pending_tags_.begin();
449 TagDeque::iterator const den = pending_tags_.end();
450 for (; dit != den; ++dit) {
452 // it was pending, so we just erase it
453 writeError("Tried to close pending tag `" + to_utf8(etag.tag_)
454 + "' when other tags were pending. Last pending tag is `"
455 + to_utf8(pending_tags_.back()->writeTag())
456 + "'. Tag discarded.");
457 pending_tags_.erase(dit);
461 // so etag isn't itself pending. is it even open?
462 if (!isTagOpen(etag)) {
463 writeError("Tried to close `" + to_utf8(etag.tag_)
464 + "' when tag was not open. Tag discarded.");
467 // ok, so etag is open.
468 // our strategy will be as below: we will do what we need to
469 // do to close this tag.
470 string estr = "Closing tag `" + to_utf8(etag.tag_)
471 + "' when other tags are pending. Discarded pending tags:\n";
472 for (dit = pending_tags_.begin(); dit != den; ++dit)
473 estr += to_utf8(xml::xmlize((*dit)->writeTag(), XMLStream::ESCAPE_ALL)) + "\n";
475 // clear the pending tags...
476 pending_tags_.clear();
477 // ...and then just fall through.
480 // make sure there are tags to be closed
481 if (tag_stack_.empty()) {
482 writeError("Tried to close `" + etag.tag_
483 + "' when no tags were open!");
487 // is the tag we are closing the last one we opened?
488 if (etag == *tag_stack_.back()) {
490 os_ << etag.writeEndTag();
491 // ...and forget about it
492 tag_stack_.pop_back();
496 // we are trying to close a tag other than the one last opened.
497 // let's first see if this particular tag is still open somehow.
498 if (!isTagOpen(etag)) {
499 writeError("Tried to close `" + etag.tag_
500 + "' when tag was not open. Tag discarded.");
504 // so the tag was opened, but other tags have been opened since
505 // and not yet closed.
506 // if it's a font tag, though...
507 if (etag.asFontTag()) {
508 // it won't be a problem if the other tags open since this one
509 // are also font tags.
510 TagDeque::const_reverse_iterator rit = tag_stack_.rbegin();
511 TagDeque::const_reverse_iterator ren = tag_stack_.rend();
512 for (; rit != ren; ++rit) {
515 if (!(*rit)->asFontTag()) {
516 // we'll just leave it and, presumably, have to close it later.
517 writeError("Unable to close font tag `" + etag.tag_
518 + "' due to open non-font tag `" + (*rit)->tag_ + "'.");
524 // <em>this is <strong>bold
525 // and are being asked to closed em. we want:
526 // <em>this is <strong>bold</strong></em><strong>
527 // first, we close the intervening tags...
528 TagPtr *curtag = &tag_stack_.back();
529 // ...remembering them in a stack.
531 while (etag != **curtag) {
532 os_ << (*curtag)->writeEndTag();
533 fontstack.push_back(*curtag);
534 tag_stack_.pop_back();
535 curtag = &tag_stack_.back();
537 os_ << etag.writeEndTag();
538 tag_stack_.pop_back();
540 // ...and restore the other tags.
541 rit = fontstack.rbegin();
542 ren = fontstack.rend();
543 for (; rit != ren; ++rit)
544 pending_tags_.push_back(*rit);
548 // it wasn't a font tag.
549 // so other tags were opened before this one and not properly closed.
550 // so we'll close them, too. that may cause other issues later, but it
551 // at least guarantees proper nesting.
552 writeError("Closing tag `" + etag.tag_
553 + "' when other tags are open, namely:");
554 TagPtr *curtag = &tag_stack_.back();
555 while (etag != **curtag) {
556 writeError((*curtag)->tag_);
557 if (**curtag != xml::parsep_tag)
558 os_ << (*curtag)->writeEndTag();
559 tag_stack_.pop_back();
560 curtag = &tag_stack_.back();
562 // curtag is now the one we actually want.
563 os_ << (*curtag)->writeEndTag();
564 tag_stack_.pop_back();
570 docstring xml::escapeString(docstring const & raw, XMLStream::EscapeSettings e)
573 bin.reserve(raw.size() * 2); // crude approximation is sufficient
574 for (size_t i = 0; i != raw.size(); ++i)
575 bin += xml::escapeChar(raw[i], e);
581 docstring const xml::uniqueID(docstring const & label)
584 static atomic_uint seed(1000);
585 return label + convert<docstring>(++seed);
589 docstring xml::cleanID(docstring const & orig)
591 // The standard xml:id only allows letters,
592 // digits, '-' and '.' in a name.
593 // This routine replaces illegal characters by '-' or '.'
594 // and adds a number for uniqueness if need be.
595 docstring const allowed = from_ascii(".-_");
597 // Use a cache of already mangled names: the alterations may merge several IDs as one. This ensures that the IDs
598 // are not mixed up in the document.
599 typedef map<docstring, docstring> MangledMap;
600 static QThreadStorage<MangledMap> tMangledNames;
601 static QThreadStorage<int> tMangleID;
603 MangledMap & mangledNames = tMangledNames.localData();
605 // If the name is already known, just return it.
606 MangledMap::const_iterator const known = mangledNames.find(orig);
607 if (known != mangledNames.end())
608 return known->second;
610 // Start creating the mangled name by iterating over the characters.
612 docstring::const_iterator it = orig.begin();
613 docstring::const_iterator end = orig.end();
615 // Make sure it starts with a letter.
616 if (!isAlphaASCII(*it) && allowed.find(*it) >= allowed.size())
620 bool mangle = false; // Indicates whether the ID had to be changed, i.e. if ID no more ensured to be unique.
621 for (; it != end; ++it) {
623 if (isAlphaASCII(c) || isDigitASCII(c) || c == '-' || c == '.'
624 || allowed.find(c) < allowed.size())
626 else if (c == '_' || c == ' ') {
630 else if (c == ':' || c == ',' || c == ';' || c == '!') {
641 int & mangleID = tMangleID.localData();
642 content += "-" + convert<docstring>(mangleID++);
645 mangledNames[orig] = content;
651 void xml::openTag(odocstream & os, string const & name, string const & attribute)
654 // This should be fixed in layout files later.
655 string param = subst(attribute, "<", "\"");
656 param = subst(param, ">", "\"");
658 // Note: we ignore the name if it empty or if it is a comment "<!-- -->" or
659 // if the name is *dummy*.
660 // We ignore dummy because dummy is not a valid docbook element and it is
661 // the internal name given to single paragraphs in the latex output.
662 // This allow us to simplify the code a lot and is a reasonable compromise.
663 if (!name.empty() && name != "!-- --" && name != "dummy") {
664 os << '<' << from_ascii(name);
666 os << ' ' << from_ascii(param);
672 void xml::closeTag(odocstream & os, string const & name)
674 if (!name.empty() && name != "!-- --" && name != "dummy")
675 os << "</" << from_ascii(name) << '>';
679 void xml::openTag(Buffer const & buf, odocstream & os,
680 OutputParams const & runparams, Paragraph const & par)
682 Layout const & style = par.layout();
683 string const & name = style.latexname();
684 string param = style.latexparam();
685 Counters & counters = buf.params().documentClass().counters();
687 string id = par.getID(buf, runparams);
691 if (param.find('#') != string::npos) {
692 string::size_type pos = param.find("id=<");
693 string::size_type end = param.find(">");
694 if( pos != string::npos && end != string::npos)
695 param.erase(pos, end-pos + 1);
697 attribute = id + ' ' + param;
699 if (param.find('#') != string::npos) {
701 if (!style.counter.empty())
702 // This uses InternalUpdate at the moment becuase xml output
703 // does not do anything with tracked counters, and it would need
704 // to track layouts if it did want to use them.
705 counters.step(style.counter, InternalUpdate);
707 counters.step(from_ascii(name), InternalUpdate);
708 int i = counters.value(from_ascii(name));
709 attribute = subst(param, "#", convert<string>(i));
714 openTag(os, name, attribute);
718 void xml::closeTag(odocstream & os, Paragraph const & par)
720 Layout const & style = par.layout();
721 closeTag(os, style.latexname());