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