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