]> git.lyx.org Git - features.git/blob - src/xml.cpp
Support the mathbbm font.
[features.git] / src / xml.cpp
1 /**
2  * \file xml.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author José Matos
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "xml.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Counters.h"
19 #include "Layout.h"
20 #include "OutputParams.h"
21 #include "Paragraph.h"
22 #include "Text.h"
23 #include "TextClass.h"
24
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"
30
31 #include <atomic>
32 #include <map>
33 #include <functional>
34 #include <QThreadStorage>
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40 namespace xml {
41
42
43 docstring escapeChar(char_type c, XMLStream::EscapeSettings e)
44 {
45         docstring str;
46         switch (e) { // For HTML: always ESCAPE_NONE. For XML: it depends, hence the parameter.
47                 case XMLStream::ESCAPE_NONE:
48                         str += c;
49                         break;
50                 case XMLStream::ESCAPE_ALL:
51                         if (c == '<') {
52                                 str += "&lt;";
53                                 break;
54                         } else if (c == '>') {
55                                 str += "&gt;";
56                                 break;
57                         }
58                         // fall through
59                 case XMLStream::ESCAPE_AND:
60                         if (c == '&')
61                                 str += "&amp;";
62                         else
63                                 str     +=c ;
64                         break;
65         }
66         return str;
67 }
68
69
70 // escape what needs escaping
71 docstring xmlize(docstring const &str, XMLStream::EscapeSettings e) {
72         odocstringstream d;
73         docstring::const_iterator it = str.begin();
74         docstring::const_iterator en = str.end();
75         for (; it != en; ++it)
76                 d << escapeChar(*it, e);
77         return d.str();
78 }
79
80
81 docstring escapeChar(char c, XMLStream::EscapeSettings e) {
82         LATTEST(static_cast<unsigned char>(c) < 0x80);
83         return escapeChar(static_cast<char_type>(c), e);
84 }
85
86
87 docstring cleanAttr(docstring const & str)
88 {
89         docstring newname;
90         docstring::const_iterator it = str.begin();
91         docstring::const_iterator en = str.end();
92         for (; it != en; ++it) {
93                 char_type const c = *it;
94                 newname += isAlnumASCII(c) ? c : char_type('_');
95         }
96         return newname;
97 }
98
99
100 docstring StartTag::writeTag() const {
101         docstring output = '<' + tag_;
102         if (!attr_.empty()) {
103                 docstring attributes = xml::xmlize(attr_, XMLStream::ESCAPE_NONE);
104                 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
105                                                           [](int c) {return !std::isspace(c);}));
106                 if (!attributes.empty()) {
107                         output += ' ' + attributes;
108                 }
109         }
110         output += ">";
111         return output;
112 }
113
114
115 docstring StartTag::writeEndTag() const {
116         return from_utf8("</") + tag_ + from_utf8(">");
117 }
118
119
120 bool StartTag::operator==(FontTag const &rhs) const {
121         return rhs == *this;
122 }
123
124
125 docstring EndTag::writeEndTag() const {
126         return from_utf8("</") + tag_ + from_utf8(">");
127 }
128
129
130 docstring CompTag::writeTag() const {
131         docstring output = '<' + from_utf8(tag_);
132         if (!attr_.empty()) {
133                 // Erase the beginning of the attributes if it contains space characters: this function deals with that
134                 // automatically.
135                 docstring attributes = xmlize(from_utf8(attr_), XMLStream::ESCAPE_NONE);
136                 attributes.erase(attributes.begin(), std::find_if(attributes.begin(), attributes.end(),
137                                                           [](int c) {return !std::isspace(c);}));
138                 if (!attributes.empty()) {
139                         output += ' ' + attributes;
140                 }
141         }
142         output += " />";
143         return output;
144 }
145
146
147 bool FontTag::operator==(StartTag const & tag) const
148 {
149         FontTag const * const ftag = tag.asFontTag();
150         if (!ftag)
151                 return false;
152         return (font_type_ == ftag->font_type_);
153 }
154
155 } // namespace xml
156
157
158 void XMLStream::writeError(std::string const &s) const {
159         LYXERR0(s);
160         os_ << from_utf8("<!-- Output Error: " + s + " -->\n");
161 }
162
163
164 void XMLStream::writeError(docstring const &s) const {
165         LYXERR0(s);
166         os_ << from_utf8("<!-- Output Error: ") << s << from_utf8(" -->\n");
167 }
168
169
170 bool XMLStream::closeFontTags() {
171         if (isTagPending(xml::parsep_tag))
172                 // we haven't had any content
173                 return true;
174
175         // this may be a useless check, since we ought at least to have
176         // the parsep_tag. but it can't hurt too much to be careful.
177         if (tag_stack_.empty())
178                 return true;
179
180         // first, we close any open font tags we can close
181         TagPtr *curtag = &tag_stack_.back();
182         while ((*curtag)->asFontTag()) {
183                 if (**curtag != xml::parsep_tag)
184                         os_ << (*curtag)->writeEndTag();
185                 tag_stack_.pop_back();
186                 // this shouldn't happen, since then the font tags
187                 // weren't in any other tag.
188 //              LASSERT(!tag_stack_.empty(), return true);
189                 if (tag_stack_.empty())
190                         return true;
191                 curtag = &tag_stack_.back();
192         }
193
194         if (**curtag == xml::parsep_tag)
195                 return true;
196
197         // so we've hit a non-font tag.
198         writeError("Tags still open in closeFontTags(). Probably not a problem,\n"
199                                            "but you might want to check these tags:");
200         TagDeque::const_reverse_iterator it = tag_stack_.rbegin();
201         TagDeque::const_reverse_iterator const en = tag_stack_.rend();
202         for (; it != en; ++it) {
203                 if (**it == xml::parsep_tag)
204                         break;
205                 writeError((*it)->tag_);
206         }
207         return false;
208 }
209
210
211 void XMLStream::startDivision(bool keep_empty) {
212         pending_tags_.push_back(makeTagPtr(xml::StartTag(xml::parsep_tag)));
213         if (keep_empty)
214                 clearTagDeque();
215 }
216
217
218 void XMLStream::endDivision() {
219         if (isTagPending(xml::parsep_tag)) {
220                 // this case is normal. it just means we didn't have content,
221                 // so the parsep_tag never got moved onto the tag stack.
222                 while (!pending_tags_.empty()) {
223                         // clear all pending tags up to and including the parsep tag.
224                         // note that we work from the back, because we want to get rid
225                         // of everything that hasn't been used.
226                         TagPtr const cur_tag = pending_tags_.back();
227                         pending_tags_.pop_back();
228                         if (*cur_tag == xml::parsep_tag)
229                                 break;
230                 }
231
232 #ifdef  XHTML_DEBUG
233                 dumpTagStack("EndDivision");
234 #endif
235
236                 return;
237         }
238
239         if (!isTagOpen(xml::parsep_tag)) {
240                 writeError("No division separation tag found in endDivision().");
241                 return;
242         }
243
244         // this case is also normal, if the parsep tag is the last one
245         // on the stack. otherwise, it's an error.
246         while (!tag_stack_.empty()) {
247                 TagPtr const cur_tag = tag_stack_.back();
248                 tag_stack_.pop_back();
249                 if (*cur_tag == xml::parsep_tag)
250                         break;
251                 writeError("Tag `" + cur_tag->tag_ + "' still open at end of paragraph. Closing.");
252                 os_ << cur_tag->writeEndTag();
253         }
254
255 #ifdef  XHTML_DEBUG
256         dumpTagStack("EndDivision");
257 #endif
258 }
259
260
261 void XMLStream::clearTagDeque() {
262         while (!pending_tags_.empty()) {
263                 TagPtr const & tag = pending_tags_.front();
264                 if (*tag != xml::parsep_tag)
265                         // tabs?
266                         os_ << tag->writeTag();
267                 tag_stack_.push_back(tag);
268                 pending_tags_.pop_front();
269         }
270 }
271
272
273 XMLStream &XMLStream::operator<<(docstring const &d) {
274         clearTagDeque();
275         os_ << xml::xmlize(d, escape_);
276         escape_ = ESCAPE_ALL;
277         return *this;
278 }
279
280
281 XMLStream &XMLStream::operator<<(const char *s) {
282         clearTagDeque();
283         docstring const d = from_ascii(s);
284         os_ << xml::xmlize(d, escape_);
285         escape_ = ESCAPE_ALL;
286         return *this;
287 }
288
289
290 XMLStream &XMLStream::operator<<(char_type c) {
291         clearTagDeque();
292         os_ << xml::escapeChar(c, escape_);
293         escape_ = ESCAPE_ALL;
294         return *this;
295 }
296
297
298 XMLStream &XMLStream::operator<<(char c) {
299         clearTagDeque();
300         os_ << xml::escapeChar(c, escape_);
301         escape_ = ESCAPE_ALL;
302         return *this;
303 }
304
305
306 XMLStream &XMLStream::operator<<(int i) {
307         clearTagDeque();
308         os_ << i;
309         escape_ = ESCAPE_ALL;
310         return *this;
311 }
312
313
314 XMLStream &XMLStream::operator<<(EscapeSettings e) {
315         escape_ = e;
316         return *this;
317 }
318
319
320 XMLStream &XMLStream::operator<<(xml::StartTag const &tag) {
321         if (tag.tag_.empty())
322                 return *this;
323         pending_tags_.push_back(makeTagPtr(tag));
324         if (tag.keepempty_)
325                 clearTagDeque();
326         return *this;
327 }
328
329
330 XMLStream &XMLStream::operator<<(xml::ParTag const &tag) {
331         if (tag.tag_.empty())
332                 return *this;
333         pending_tags_.push_back(makeTagPtr(tag));
334         return *this;
335 }
336
337
338 XMLStream &XMLStream::operator<<(xml::CompTag const &tag) {
339         if (tag.tag_.empty())
340                 return *this;
341         clearTagDeque();
342         os_ << tag.writeTag();
343         return *this;
344 }
345
346
347 XMLStream &XMLStream::operator<<(xml::FontTag const &tag) {
348         if (tag.tag_.empty())
349                 return *this;
350         pending_tags_.push_back(makeTagPtr(tag));
351         return *this;
352 }
353
354
355 XMLStream &XMLStream::operator<<(xml::CR const &) {
356         clearTagDeque();
357         os_ << from_ascii("\n");
358         return *this;
359 }
360
361
362 bool XMLStream::isTagOpen(xml::StartTag const &stag, int maxdepth) const {
363         auto sit = tag_stack_.begin();
364         auto sen = tag_stack_.cend();
365         for (; sit != sen && maxdepth != 0; ++sit) {
366                 if (**sit == stag)
367                         return true;
368                 maxdepth -= 1;
369         }
370         return false;
371 }
372
373
374 bool XMLStream::isTagOpen(xml::EndTag const &etag, int maxdepth) const {
375         auto sit = tag_stack_.begin();
376         auto sen = tag_stack_.cend();
377         for (; sit != sen && maxdepth != 0; ++sit) {
378                 if (etag == **sit)
379                         return true;
380                 maxdepth -= 1;
381         }
382         return false;
383 }
384
385
386 bool XMLStream::isTagPending(xml::StartTag const &stag, int maxdepth) const {
387         auto sit = pending_tags_.begin();
388         auto sen = pending_tags_.cend();
389         for (; sit != sen && maxdepth != 0; ++sit) {
390                 if (**sit == stag)
391                         return true;
392                 maxdepth -= 1;
393         }
394         return false;
395 }
396
397
398 // this is complicated, because we want to make sure that
399 // everything is properly nested. the code ought to make
400 // sure of that, but we won't assert (yet) if we run into
401 // a problem. we'll just output error messages and try our
402 // best to make things work.
403 XMLStream &XMLStream::operator<<(xml::EndTag const &etag) {
404         if (etag.tag_.empty())
405                 return *this;
406
407         // if this tag is pending, we can simply discard it.
408         if (!pending_tags_.empty()) {
409                 if (etag == *pending_tags_.back()) {
410                         // we have <tag></tag>, so we discard it and remove it
411                         // from the pending_tags_.
412                         pending_tags_.pop_back();
413                         return *this;
414                 }
415
416                 // there is a pending tag that isn't the one we are trying
417                 // to close.
418
419                 // is this tag itself pending?
420                 // non-const iterators because we may call erase().
421                 TagDeque::iterator dit = pending_tags_.begin();
422                 TagDeque::iterator const den = pending_tags_.end();
423                 for (; dit != den; ++dit) {
424                         if (etag == **dit) {
425                                 // it was pending, so we just erase it
426                                 writeError("Tried to close pending tag `" + to_utf8(etag.tag_)
427                                                    + "' when other tags were pending. Last pending tag is `"
428                                                    + to_utf8(pending_tags_.back()->writeTag())
429                                                    + "'. Tag discarded.");
430                                 pending_tags_.erase(dit);
431                                 return *this;
432                         }
433                 }
434                 // so etag isn't itself pending. is it even open?
435                 if (!isTagOpen(etag)) {
436                         writeError("Tried to close `" + to_utf8(etag.tag_)
437                                            + "' when tag was not open. Tag discarded.");
438                         return *this;
439                 }
440                 // ok, so etag is open.
441                 // our strategy will be as below: we will do what we need to
442                 // do to close this tag.
443                 string estr = "Closing tag `" + to_utf8(etag.tag_)
444                                           + "' when other tags are pending. Discarded pending tags:\n";
445                 for (dit = pending_tags_.begin(); dit != den; ++dit)
446                         estr += to_utf8(xml::xmlize((*dit)->writeTag(), XMLStream::ESCAPE_ALL)) + "\n";
447                 writeError(estr);
448                 // clear the pending tags...
449                 pending_tags_.clear();
450                 // ...and then just fall through.
451         }
452
453         // make sure there are tags to be closed
454         if (tag_stack_.empty()) {
455                 writeError("Tried to close `" + etag.tag_
456                                    + "' when no tags were open!");
457                 return *this;
458         }
459
460         // is the tag we are closing the last one we opened?
461         if (etag == *tag_stack_.back()) {
462                 // output it...
463                 os_ << etag.writeEndTag();
464                 // ...and forget about it
465                 tag_stack_.pop_back();
466                 return *this;
467         }
468
469         // we are trying to close a tag other than the one last opened.
470         // let's first see if this particular tag is still open somehow.
471         if (!isTagOpen(etag)) {
472                 writeError("Tried to close `" + etag.tag_
473                                    + "' when tag was not open. Tag discarded.");
474                 return *this;
475         }
476
477         // so the tag was opened, but other tags have been opened since
478         // and not yet closed.
479         // if it's a font tag, though...
480         if (etag.asFontTag()) {
481                 // it won't be a problem if the other tags open since this one
482                 // are also font tags.
483                 TagDeque::const_reverse_iterator rit = tag_stack_.rbegin();
484                 TagDeque::const_reverse_iterator ren = tag_stack_.rend();
485                 for (; rit != ren; ++rit) {
486                         if (etag == **rit)
487                                 break;
488                         if (!(*rit)->asFontTag()) {
489                                 // we'll just leave it and, presumably, have to close it later.
490                                 writeError("Unable to close font tag `" + etag.tag_
491                                                    + "' due to open non-font tag `" + (*rit)->tag_ + "'.");
492                                 return *this;
493                         }
494                 }
495
496                 // so we have e.g.:
497                 //    <em>this is <strong>bold
498                 // and are being asked to closed em. we want:
499                 //    <em>this is <strong>bold</strong></em><strong>
500                 // first, we close the intervening tags...
501                 TagPtr *curtag = &tag_stack_.back();
502                 // ...remembering them in a stack.
503                 TagDeque fontstack;
504                 while (etag != **curtag) {
505                         os_ << (*curtag)->writeEndTag();
506                         fontstack.push_back(*curtag);
507                         tag_stack_.pop_back();
508                         curtag = &tag_stack_.back();
509                 }
510                 os_ << etag.writeEndTag();
511                 tag_stack_.pop_back();
512
513                 // ...and restore the other tags.
514                 rit = fontstack.rbegin();
515                 ren = fontstack.rend();
516                 for (; rit != ren; ++rit)
517                         pending_tags_.push_back(*rit);
518                 return *this;
519         }
520
521         // it wasn't a font tag.
522         // so other tags were opened before this one and not properly closed.
523         // so we'll close them, too. that may cause other issues later, but it
524         // at least guarantees proper nesting.
525         writeError("Closing tag `" + etag.tag_
526                            + "' when other tags are open, namely:");
527         TagPtr *curtag = &tag_stack_.back();
528         while (etag != **curtag) {
529                 writeError((*curtag)->tag_);
530                 if (**curtag != xml::parsep_tag)
531                         os_ << (*curtag)->writeEndTag();
532                 tag_stack_.pop_back();
533                 curtag = &tag_stack_.back();
534         }
535         // curtag is now the one we actually want.
536         os_ << (*curtag)->writeEndTag();
537         tag_stack_.pop_back();
538
539         return *this;
540 }
541
542
543 docstring xml::escapeString(docstring const & raw, XMLStream::EscapeSettings e)
544 {
545         docstring bin;
546         bin.reserve(raw.size() * 2); // crude approximation is sufficient
547         for (size_t i = 0; i != raw.size(); ++i)
548                 bin += xml::escapeChar(raw[i], e);
549
550         return bin;
551 }
552
553
554 docstring const xml::uniqueID(docstring const & label)
555 {
556         // thread-safe
557         static atomic_uint seed(1000);
558         return label + convert<docstring>(++seed);
559 }
560
561
562 docstring xml::cleanID(docstring const & orig)
563 {
564         // The standard xml:id only allows letters,
565         // digits, '-' and '.' in a name.
566         // This routine replaces illegal characters by '-' or '.'
567         // and adds a number for uniqueness if need be.
568         docstring const allowed = from_ascii(".-_");
569
570         // Use a cache of already mangled names: the alterations may merge several IDs as one. This ensures that the IDs
571         // are not mixed up in the document.
572         typedef map<docstring, docstring> MangledMap;
573         static QThreadStorage<MangledMap> tMangledNames;
574         static QThreadStorage<int> tMangleID;
575
576         MangledMap & mangledNames = tMangledNames.localData();
577
578         // If the name is already known, just return it.
579         MangledMap::const_iterator const known = mangledNames.find(orig);
580         if (known != mangledNames.end())
581                 return known->second;
582
583         // Start creating the mangled name by iterating over the characters.
584         docstring content;
585         docstring::const_iterator it  = orig.begin();
586         docstring::const_iterator end = orig.end();
587
588         // Make sure it starts with a letter.
589         if (!isAlphaASCII(*it) && allowed.find(*it) >= allowed.size())
590                 content += "x";
591
592         // Do the mangling.
593         bool mangle = false; // Indicates whether the ID had to be changed, i.e. if ID no more ensured to be unique.
594         for (; it != end; ++it) {
595                 char_type c = *it;
596                 if (isAlphaASCII(c) || isDigitASCII(c) || c == '-' || c == '.'
597                       || allowed.find(c) < allowed.size())
598                         content += c;
599                 else if (c == '_' || c == ' ') {
600                         mangle = true;
601                         content += "-";
602                 }
603                 else if (c == ':' || c == ',' || c == ';' || c == '!') {
604                         mangle = true;
605                         content += ".";
606                 }
607                 else {
608                         mangle = true;
609                         content += "-";
610                 }
611         }
612
613         if (mangle) {
614                 int & mangleID = tMangleID.localData();
615                 content += "-" + convert<docstring>(mangleID++);
616         }
617
618         mangledNames[orig] = content;
619
620         return content;
621 }
622
623
624 void xml::openTag(odocstream & os, string const & name, string const & attribute)
625 {
626     // FIXME UNICODE
627     // This should be fixed in layout files later.
628     string param = subst(attribute, "<", "\"");
629     param = subst(param, ">", "\"");
630
631     // Note: we ignore the name if it empty or if it is a comment "<!-- -->" or
632     // if the name is *dummy*.
633     // We ignore dummy because dummy is not a valid docbook element and it is
634     // the internal name given to single paragraphs in the latex output.
635     // This allow us to simplify the code a lot and is a reasonable compromise.
636     if (!name.empty() && name != "!-- --" && name != "dummy") {
637         os << '<' << from_ascii(name);
638         if (!param.empty())
639             os << ' ' << from_ascii(param);
640         os << '>';
641     }
642 }
643
644
645 void xml::closeTag(odocstream & os, string const & name)
646 {
647     if (!name.empty() && name != "!-- --" && name != "dummy")
648         os << "</" << from_ascii(name) << '>';
649 }
650
651
652 void xml::openTag(Buffer const & buf, odocstream & os,
653                    OutputParams const & runparams, Paragraph const & par)
654 {
655     Layout const & style = par.layout();
656     string const & name = style.latexname();
657     string param = style.latexparam();
658     Counters & counters = buf.params().documentClass().counters();
659
660     string id = par.getID(buf, runparams);
661
662     string attribute;
663     if (!id.empty()) {
664         if (param.find('#') != string::npos) {
665             string::size_type pos = param.find("id=<");
666             string::size_type end = param.find(">");
667             if( pos != string::npos && end != string::npos)
668                 param.erase(pos, end-pos + 1);
669         }
670         attribute = id + ' ' + param;
671     } else {
672         if (param.find('#') != string::npos) {
673             // FIXME UNICODE
674             if (!style.counter.empty())
675                 // This uses InternalUpdate at the moment becuase xml output
676                 // does not do anything with tracked counters, and it would need
677                 // to track layouts if it did want to use them.
678                 counters.step(style.counter, InternalUpdate);
679             else
680                 counters.step(from_ascii(name), InternalUpdate);
681             int i = counters.value(from_ascii(name));
682             attribute = subst(param, "#", convert<string>(i));
683         } else {
684             attribute = param;
685         }
686     }
687     openTag(os, name, attribute);
688 }
689
690
691 void xml::closeTag(odocstream & os, Paragraph const & par)
692 {
693     Layout const & style = par.layout();
694     closeTag(os, style.latexname());
695 }
696
697
698 } // namespace lyx