]> git.lyx.org Git - lyx.git/blob - src/output_docbook.cpp
58e1b810f1b43cd4e6b0fd1e52b39eb3703a67f9
[lyx.git] / src / output_docbook.cpp
1 /**
2  * \file output_docbook.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author José Matos
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "output_docbook.h"
15
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "Font.h"
20 #include "InsetList.h"
21 #include "Paragraph.h"
22 #include "ParagraphList.h"
23 #include "ParagraphParameters.h"
24 #include "xml.h"
25 #include "Text.h"
26 #include "TextClass.h"
27
28 #include "insets/InsetBibtex.h"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetLabel.h"
31 #include "mathed/InsetMath.h"
32 #include "insets/InsetNote.h"
33
34 #include "support/lassert.h"
35 #include "support/textutils.h"
36
37 #include <stack>
38 #include <iostream>
39 #include <algorithm>
40 #include <sstream>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47 namespace {
48
49 std::string fontToDocBookTag(xml::FontTypes type)
50 {
51         switch (type) {
52         case xml::FontTypes::FT_EMPH:
53         case xml::FontTypes::FT_BOLD:
54                 return "emphasis";
55         case xml::FontTypes::FT_NOUN:
56                 return "personname";
57         case xml::FontTypes::FT_UBAR:
58         case xml::FontTypes::FT_WAVE:
59         case xml::FontTypes::FT_DBAR:
60         case xml::FontTypes::FT_SOUT:
61         case xml::FontTypes::FT_XOUT:
62         case xml::FontTypes::FT_ITALIC:
63         case xml::FontTypes::FT_UPRIGHT:
64         case xml::FontTypes::FT_SLANTED:
65         case xml::FontTypes::FT_SMALLCAPS:
66         case xml::FontTypes::FT_ROMAN:
67         case xml::FontTypes::FT_SANS:
68                 return "emphasis";
69         case xml::FontTypes::FT_TYPE:
70                 return "code";
71         case xml::FontTypes::FT_SIZE_TINY:
72         case xml::FontTypes::FT_SIZE_SCRIPT:
73         case xml::FontTypes::FT_SIZE_FOOTNOTE:
74         case xml::FontTypes::FT_SIZE_SMALL:
75         case xml::FontTypes::FT_SIZE_NORMAL:
76         case xml::FontTypes::FT_SIZE_LARGE:
77         case xml::FontTypes::FT_SIZE_LARGER:
78         case xml::FontTypes::FT_SIZE_LARGEST:
79         case xml::FontTypes::FT_SIZE_HUGE:
80         case xml::FontTypes::FT_SIZE_HUGER:
81         case xml::FontTypes::FT_SIZE_INCREASE:
82         case xml::FontTypes::FT_SIZE_DECREASE:
83                 return "emphasis";
84         default:
85                 return "";
86         }
87 }
88
89
90 string fontToRole(xml::FontTypes type)
91 {
92         // Specific fonts are achieved with roles. The only common ones are "" for basic emphasis,
93         // and "bold"/"strong" for bold. With some specific options, other roles are copied into
94         // HTML output (via the DocBook XSLT sheets); otherwise, if not recognised, they are just ignored.
95         // Hence, it is not a problem to have many roles by default here.
96         // See https://www.sourceware.org/ml/docbook/2003-05/msg00269.html
97         switch (type) {
98         case xml::FontTypes::FT_ITALIC:
99         case xml::FontTypes::FT_EMPH:
100                 return "";
101         case xml::FontTypes::FT_BOLD:
102                 return "bold";
103         case xml::FontTypes::FT_NOUN: // Outputs a <person>
104         case xml::FontTypes::FT_TYPE: // Outputs a <code>
105                 return "";
106         case xml::FontTypes::FT_UBAR:
107                 return "underline";
108
109         // All other roles are non-standard for DocBook.
110
111         case xml::FontTypes::FT_WAVE:
112                 return "wave";
113         case xml::FontTypes::FT_DBAR:
114                 return "dbar";
115         case xml::FontTypes::FT_SOUT:
116                 return "sout";
117         case xml::FontTypes::FT_XOUT:
118                 return "xout";
119         case xml::FontTypes::FT_UPRIGHT:
120                 return "upright";
121         case xml::FontTypes::FT_SLANTED:
122                 return "slanted";
123         case xml::FontTypes::FT_SMALLCAPS:
124                 return "smallcaps";
125         case xml::FontTypes::FT_ROMAN:
126                 return "roman";
127         case xml::FontTypes::FT_SANS:
128                 return "sans";
129         case xml::FontTypes::FT_SIZE_TINY:
130                 return "tiny";
131         case xml::FontTypes::FT_SIZE_SCRIPT:
132                 return "size_script";
133         case xml::FontTypes::FT_SIZE_FOOTNOTE:
134                 return "size_footnote";
135         case xml::FontTypes::FT_SIZE_SMALL:
136                 return "size_small";
137         case xml::FontTypes::FT_SIZE_NORMAL:
138                 return "size_normal";
139         case xml::FontTypes::FT_SIZE_LARGE:
140                 return "size_large";
141         case xml::FontTypes::FT_SIZE_LARGER:
142                 return "size_larger";
143         case xml::FontTypes::FT_SIZE_LARGEST:
144                 return "size_largest";
145         case xml::FontTypes::FT_SIZE_HUGE:
146                 return "size_huge";
147         case xml::FontTypes::FT_SIZE_HUGER:
148                 return "size_huger";
149         case xml::FontTypes::FT_SIZE_INCREASE:
150                 return "size_increase";
151         case xml::FontTypes::FT_SIZE_DECREASE:
152                 return "size_decrease";
153         default:
154                 return "";
155         }
156 }
157
158
159 string fontToAttribute(xml::FontTypes type) {
160         // If there is a role (i.e. nonstandard use of a tag), output the attribute. Otherwise, the sheer tag is sufficient
161         // for the font.
162         string role = fontToRole(type);
163         if (!role.empty()) {
164                 return "role='" + role + "'";
165         } else {
166                 return "";
167         }
168 }
169
170
171 // Convenience functions to open and close tags. First, very low-level ones to ensure a consistent new-line behaviour.
172 // Block style:
173 //        Content before
174 //        <blocktag>
175 //          Contents of the block.
176 //        </blocktag>
177 //        Content after
178 // Paragraph style:
179 //        Content before
180 //          <paratag>Contents of the paragraph.</paratag>
181 //        Content after
182 // Inline style:
183 //    Content before<inlinetag>Contents of the paragraph.</inlinetag>Content after
184
185 void openInlineTag(XMLStream & xs, const std::string & tag, const std::string & attr)
186 {
187         xs << xml::StartTag(tag, attr);
188 }
189
190
191 void closeInlineTag(XMLStream & xs, const std::string & tag)
192 {
193         xs << xml::EndTag(tag);
194 }
195
196
197 void openParTag(XMLStream & xs, const std::string & tag, const std::string & attr)
198 {
199         if (!xs.isLastTagCR())
200                 xs << xml::CR();
201         xs << xml::StartTag(tag, attr);
202 }
203
204
205 void closeParTag(XMLStream & xs, const std::string & tag)
206 {
207         xs << xml::EndTag(tag);
208         xs << xml::CR();
209 }
210
211
212 void openBlockTag(XMLStream & xs, const std::string & tag, const std::string & attr)
213 {
214         if (!xs.isLastTagCR())
215                 xs << xml::CR();
216         xs << xml::StartTag(tag, attr);
217         xs << xml::CR();
218 }
219
220
221 void closeBlockTag(XMLStream & xs, const std::string & tag)
222 {
223         if (!xs.isLastTagCR())
224                 xs << xml::CR();
225         xs << xml::EndTag(tag);
226         xs << xml::CR();
227 }
228
229
230 void openTag(XMLStream & xs, const std::string & tag, const std::string & attr, const std::string & tagtype)
231 {
232         if (tag.empty() || tag == "NONE") // Common check to be performed elsewhere, if it was not here.
233                 return;
234
235         if (tag == "para" || tagtype == "paragraph") // Special case for <para>: always considered as a paragraph.
236                 openParTag(xs, tag, attr);
237         else if (tagtype == "block")
238                 openBlockTag(xs, tag, attr);
239         else if (tagtype == "inline")
240                 openInlineTag(xs, tag, attr);
241         else
242                 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + tag + " " + attr + "'");
243 }
244
245
246 void closeTag(XMLStream & xs, const std::string & tag, const std::string & tagtype)
247 {
248         if (tag.empty() || tag == "NONE")
249                 return;
250
251         if (tag == "para" || tagtype == "paragraph") // Special case for <para>: always considered as a paragraph.
252                 closeParTag(xs, tag);
253         else if (tagtype == "block")
254                 closeBlockTag(xs, tag);
255         else if (tagtype == "inline")
256                 closeInlineTag(xs, tag);
257         else
258                 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + tag + "'");
259 }
260
261
262 void compTag(XMLStream & xs, const std::string & tag, const std::string & attr, const std::string & tagtype)
263 {
264         if (tag.empty() || tag == "NONE")
265                 return;
266
267         // Special case for <para>: always considered as a paragraph.
268         if (tag == "para" || tagtype == "paragraph" || tagtype == "block") {
269                 if (!xs.isLastTagCR())
270                         xs << xml::CR();
271                 xs << xml::CompTag(tag, attr);
272                 xs << xml::CR();
273         } else if (tagtype == "inline") {
274                 xs << xml::CompTag(tag, attr);
275         } else {
276                 xs.writeError("Unrecognised tag type '" + tagtype + "' for '" + tag + "'");
277         }
278 }
279
280
281 // Higher-level convenience functions.
282
283 void openParTag(XMLStream & xs, const Paragraph * par, const Paragraph * prevpar)
284 {
285         if (par == prevpar)
286                 prevpar = nullptr;
287
288         // When should the wrapper be opened here? Only if the previous paragraph has the SAME wrapper tag
289         // (usually, they won't have the same layout) and the CURRENT one allows merging.
290         // The main use case is author information in several paragraphs: if the name of the author is the
291         // first paragraph of an author, then merging with the previous tag does not make sense. Say the
292         // next paragraph is the affiliation, then it should be output in the same <author> tag (different
293         // layout, same wrapper tag).
294         Layout const & lay = par->layout();
295         bool openWrapper = lay.docbookwrappertag() != "NONE";
296         if (prevpar != nullptr) {
297                 Layout const & prevlay = prevpar->layout();
298                 if (prevlay.docbookwrappertag() != "NONE") {
299                         if (prevlay.docbookwrappertag() == lay.docbookwrappertag() &&
300                                         prevlay.docbookwrapperattr() == lay.docbookwrapperattr())
301                                 openWrapper = !lay.docbookwrappermergewithprevious();
302                         else
303                                 openWrapper = true;
304                 }
305         }
306
307         // Main logic.
308         if (openWrapper)
309                 openTag(xs, lay.docbookwrappertag(), lay.docbookwrapperattr(), lay.docbookwrappertagtype());
310
311         const string & tag = lay.docbooktag();
312         if (tag != "NONE") {
313                 auto xmltag = xml::ParTag(tag, lay.docbookattr());
314                 if (!xs.isTagOpen(xmltag, 1)) { // Don't nest a paragraph directly in a paragraph.
315                         // TODO: required or not?
316                         // TODO: avoid creating a ParTag object just for this query...
317                         openTag(xs, lay.docbooktag(), lay.docbookattr(), lay.docbooktagtype());
318                         openTag(xs, lay.docbookinnertag(), lay.docbookinnerattr(), lay.docbookinnertagtype());
319                 }
320         }
321
322         openTag(xs, lay.docbookitemtag(), lay.docbookitemattr(), lay.docbookitemtagtype());
323         openTag(xs, lay.docbookiteminnertag(), lay.docbookiteminnerattr(), lay.docbookiteminnertagtype());
324 }
325
326
327 void closeParTag(XMLStream & xs, Paragraph const * par, Paragraph const * nextpar)
328 {
329         if (par == nextpar)
330                 nextpar = nullptr;
331
332         // See comment in openParTag.
333         Layout const & lay = par->layout();
334         bool closeWrapper = lay.docbookwrappertag() != "NONE";
335         if (nextpar != nullptr) {
336                 Layout const & nextlay = nextpar->layout();
337                 if (nextlay.docbookwrappertag() != "NONE") {
338                         if (nextlay.docbookwrappertag() == lay.docbookwrappertag() &&
339                                         nextlay.docbookwrapperattr() == lay.docbookwrapperattr())
340                                 closeWrapper = !nextlay.docbookwrappermergewithprevious();
341                         else
342                                 closeWrapper = true;
343                 }
344         }
345
346         // Main logic.
347         closeTag(xs, lay.docbookiteminnertag(), lay.docbookiteminnertagtype());
348         closeTag(xs, lay.docbookitemtag(), lay.docbookitemtagtype());
349         closeTag(xs, lay.docbookinnertag(), lay.docbookinnertagtype());
350         closeTag(xs, lay.docbooktag(), lay.docbooktagtype());
351         if (closeWrapper)
352                 closeTag(xs, lay.docbookwrappertag(), lay.docbookwrappertagtype());
353 }
354
355
356 void makeBibliography(
357                 Text const & text,
358                 Buffer const & buf,
359                 XMLStream & xs,
360                 OutputParams const & runparams,
361                 ParagraphList::const_iterator const & par)
362 {
363         // If this is the first paragraph in a bibliography, open the bibliography tag.
364         auto const * pbegin_before = text.paragraphs().getParagraphBefore(par);
365         if (pbegin_before == nullptr || (pbegin_before && pbegin_before->layout().latextype != LATEX_BIB_ENVIRONMENT)) {
366                 xs << xml::StartTag("bibliography");
367                 xs << xml::CR();
368         }
369
370         // Start the precooked bibliography entry. This is very much like opening a paragraph tag.
371         // Don't forget the citation ID!
372         docstring attr;
373         for (auto i = 0; i < par->size(); ++i) {
374                 Inset const *ip = par->getInset(i);
375                 if (!ip)
376                         continue;
377                 if (const auto * bibitem = dynamic_cast<const InsetBibitem*>(ip)) {
378                         auto id = xml::cleanID(bibitem->getParam("key"));
379                         attr = from_utf8("xml:id='") + id + from_utf8("'");
380                         break;
381                 }
382         }
383         xs << xml::StartTag(from_utf8("bibliomixed"), attr);
384
385         // Generate the entry. Concatenate the different parts of the paragraph if any.
386         auto const begin = text.paragraphs().begin();
387         auto pars = par->simpleDocBookOnePar(buf, runparams, text.outerFont(std::distance(begin, par)), 0);
388         for (auto & parXML : pars)
389                 xs << XMLStream::ESCAPE_NONE << parXML;
390
391         // End the precooked bibliography entry.
392         xs << xml::EndTag("bibliomixed");
393         xs << xml::CR();
394
395         // If this is the last paragraph in a bibliography, close the bibliography tag.
396         auto const end = text.paragraphs().end();
397         auto nextpar = par;
398         ++nextpar;
399         bool endBibliography = nextpar == end || nextpar->layout().latextype != LATEX_BIB_ENVIRONMENT;
400
401         if (endBibliography) {
402                 xs << xml::EndTag("bibliography");
403                 xs << xml::CR();
404         }
405 }
406
407
408 void makeParagraph(
409                 Text const & text,
410                 Buffer const & buf,
411                 XMLStream & xs,
412                 OutputParams const & runparams,
413                 ParagraphList::const_iterator const & par)
414 {
415         auto const begin = text.paragraphs().begin();
416         auto const end = text.paragraphs().end();
417         auto prevpar = text.paragraphs().getParagraphBefore(par);
418
419         // We want to open the paragraph tag if:
420         //   (i) the current layout permits multiple paragraphs
421         //  (ii) we are either not already inside a paragraph (HTMLIsBlock) OR
422         //         we are, but this is not the first paragraph
423         //
424         // But there is also a special case, and we first see whether we are in it.
425         // We do not want to open the paragraph tag if this paragraph contains
426         // only one item, and that item is "inline", i.e., not HTMLIsBlock (such
427         // as a branch). On the other hand, if that single item has a font change
428         // applied to it, then we still do need to open the paragraph.
429         //
430         // Obviously, this is very fragile. The main reason we need to do this is
431         // because of branches, e.g., a branch that contains an entire new section.
432         // We do not really want to wrap that whole thing in a <div>...</div>.
433         bool special_case = false;
434         Inset const *specinset = par->size() == 1 ? par->getInset(0) : nullptr;
435         if (specinset && !specinset->getLayout().htmlisblock()) { // TODO: Convert htmlisblock to a DocBook parameter?
436                 Layout const &style = par->layout();
437                 FontInfo const first_font = style.labeltype == LABEL_MANUAL ?
438                                                                         style.labelfont : style.font;
439                 FontInfo const our_font =
440                                 par->getFont(buf.masterBuffer()->params(), 0,
441                                                          text.outerFont(std::distance(begin, par))).fontInfo();
442
443                 if (first_font == our_font)
444                         special_case = true;
445         }
446
447         size_t nInsets = std::distance(par->insetList().begin(), par->insetList().end());
448
449         // Plain layouts must be ignored.
450         special_case |= buf.params().documentClass().isPlainLayout(par->layout()) && !runparams.docbook_force_pars;
451         // Equations do not deserve their own paragraph (DocBook allows them outside paragraphs).
452         // Exception: any case that generates an <inlineequation> must still get a paragraph to be valid.
453         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
454                 return inset.inset && inset.inset->asInsetMath() && inset.inset->asInsetMath()->getType() != hullSimple;
455         });
456         // Tables doe not deserve their own paragraphs (DocBook allows them outside paragraphs).
457         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
458                 return inset.inset->lyxCode() == TABULAR_CODE;
459         });
460         // Floats cannot be in paragraphs.
461         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
462                 return inset.inset->lyxCode() == FLOAT_CODE;
463         });
464         // Bibliographies cannot be in paragraphs. Bibitems should still be handled as paragraphs, though
465         // (see makeParagraphBibliography).
466         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
467                 return inset.inset->lyxCode() == BIBTEX_CODE;
468         });
469         // ERTs are in comments, not paragraphs.
470         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
471                 return inset.inset->lyxCode() == ERT_CODE;
472         });
473         // Listings should not get into their own paragraph.
474         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
475                 return inset.inset->lyxCode() == LISTINGS_CODE;
476         });
477         // Boxes cannot get into their own paragraph.
478         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
479                 return inset.inset->lyxCode() == BOX_CODE;
480         });
481         // Includes should not have a paragraph.
482         special_case |= nInsets == (size_t) par->size() && std::all_of(par->insetList().begin(), par->insetList().end(), [](InsetList::Element inset) {
483                 return inset.inset->lyxCode() == INCLUDE_CODE;
484         });
485
486         bool const open_par = runparams.docbook_make_pars
487                                                   && !runparams.docbook_in_par
488                                                   && !special_case;
489
490         // We want to issue the closing tag if either:
491         //   (i)  We opened it, and either docbook_in_par is false,
492         //              or we're not in the last paragraph, anyway.
493         //   (ii) We didn't open it and docbook_in_par is true,
494         //              but we are in the first par, and there is a next par.
495         bool const close_par = open_par && (!runparams.docbook_in_par);
496
497         // Determine if this paragraph has some real content. Things like new pages are not caught
498         // by Paragraph::empty(), even though they do not generate anything useful in DocBook.
499         // Thus, remove all spaces (including new lines: \r, \n) before checking for emptiness.
500         // std::all_of allows doing this check without having to copy the string.
501         // Open and close tags around each contained paragraph.
502         auto nextpar = par;
503         ++nextpar;
504         auto pars = par->simpleDocBookOnePar(buf, runparams, text.outerFont(distance(begin, par)), 0, nextpar == end, special_case);
505         for (docstring const & parXML : pars) {
506                 if (xml::isNotOnlySpace(parXML)) {
507                         if (open_par)
508                                 openParTag(xs, &*par, prevpar);
509
510                         xs << XMLStream::ESCAPE_NONE << parXML;
511
512                         if (close_par)
513                                 closeParTag(xs, &*par, (nextpar != end) ? &*nextpar : nullptr);
514                 }
515         }
516 }
517
518
519 void makeEnvironment(Text const &text,
520                                          Buffer const &buf,
521                      XMLStream &xs,
522                      OutputParams const &runparams,
523                      ParagraphList::const_iterator const & par)
524 {
525         auto const end = text.paragraphs().end();
526         auto nextpar = par;
527         ++nextpar;
528
529         // Special cases for listing-like environments provided in layouts. This is quite ad-hoc, but provides a useful
530         // default. This should not be used by too many environments (only LyX-Code right now).
531         // This would be much simpler if LyX-Code was implemented as InsetListings...
532         bool mimicListing = false;
533         bool ignoreFonts = false;
534         if (par->layout().docbooktag() == "programlisting") {
535                 mimicListing = true;
536                 ignoreFonts = true;
537         }
538
539         // Output the opening tag for this environment, but only if it has not been previously opened (condition
540         // implemented in openParTag).
541         auto prevpar = text.paragraphs().getParagraphBefore(par);
542         openParTag(xs, &*par, prevpar); // TODO: switch in layout for par/block?
543
544         // Generate the contents of this environment. There is a special case if this is like some environment.
545         Layout const & style = par->layout();
546         if (style.latextype == LATEX_COMMAND) {
547                 // Nothing to do (otherwise, infinite loops).
548         } else if (style.latextype == LATEX_ENVIRONMENT) {
549                 // Generate the paragraph, if need be.
550                 auto pars = par->simpleDocBookOnePar(buf, runparams, text.outerFont(std::distance(text.paragraphs().begin(), par)), 0, false, ignoreFonts);
551
552                 if (mimicListing) {
553                         auto p = pars.begin();
554                         while (p != pars.end()) {
555                                 openTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnerattr(), par->layout().docbookiteminnertagtype());
556                                 xs << XMLStream::ESCAPE_NONE << *p;
557                                 closeTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnertagtype());
558                                 ++p;
559
560                                 // Insert a new line after each "paragraph" (i.e. line in the listing), except for the last one.
561                                 // Otherwise, there would one more new line in the output than in the LyX document.
562                                 if (p != pars.end())
563                                         xs << xml::CR();
564                         }
565                 } else {
566                         for (auto const & p : pars) {
567                                 openTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnerattr(), par->layout().docbookiteminnertagtype());
568                                 xs << XMLStream::ESCAPE_NONE << p;
569                                 closeTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnertagtype());
570                         }
571                 }
572         } else {
573                 makeAny(text, buf, xs, runparams, par);
574         }
575
576         // Close the environment.
577         closeParTag(xs, &*par, (nextpar != end) ? &*nextpar : nullptr); // TODO: switch in layout for par/block?
578 }
579
580
581 ParagraphList::const_iterator findEndOfEnvironment(
582                 ParagraphList::const_iterator const & pstart,
583                 ParagraphList::const_iterator const & pend)
584 {
585         // Copy-paste from XHTML. Should be factored out at some point...
586         ParagraphList::const_iterator p = pstart;
587         Layout const & bstyle = p->layout();
588         size_t const depth = p->params().depth();
589         for (++p; p != pend; ++p) {
590                 Layout const & style = p->layout();
591                 // It shouldn't happen that e.g. a section command occurs inside
592                 // a quotation environment, at a higher depth, but as of 6/2009,
593                 // it can happen. We pretend that it's just at lowest depth.
594                 if (style.latextype == LATEX_COMMAND)
595                         return p;
596
597                 // If depth is down, we're done
598                 if (p->params().depth() < depth)
599                         return p;
600
601                 // If depth is up, we're not done
602                 if (p->params().depth() > depth)
603                         continue;
604
605                 // FIXME I am not sure about the first check.
606                 // Surely we *could* have different layouts that count as
607                 // LATEX_PARAGRAPH, right?
608                 if (style.latextype == LATEX_PARAGRAPH || style != bstyle)
609                         return p;
610         }
611         return pend;
612 }
613
614
615 ParagraphList::const_iterator makeListEnvironment(Text const &text,
616                                                                                                   Buffer const &buf,
617                                                           XMLStream &xs,
618                                                           OutputParams const &runparams,
619                                                           ParagraphList::const_iterator const & begin)
620 {
621         auto par = begin;
622         auto const end = text.paragraphs().end();
623         auto const envend = findEndOfEnvironment(par, end);
624
625         // Output the opening tag for this environment.
626         Layout const & envstyle = par->layout();
627         openTag(xs, envstyle.docbookwrappertag(), envstyle.docbookwrapperattr(), envstyle.docbookwrappertagtype());
628         openTag(xs, envstyle.docbooktag(), envstyle.docbookattr(), envstyle.docbooktagtype());
629
630         // Handle the content of the list environment, item by item.
631         while (par != envend) {
632                 // Skip this paragraph if it is both empty and the last one (otherwise, there may be deeper paragraphs after).
633                 auto nextpar = par;
634                 ++nextpar;
635                 if (par->empty() && nextpar == envend)
636                         break;
637
638                 // Open the item wrapper.
639                 Layout const & style = par->layout();
640                 openTag(xs, style.docbookitemwrappertag(), style.docbookitemwrapperattr(), style.docbookitemwrappertagtype());
641
642                 // Generate the label, if need be. If it is taken from the text, sep != 0 and corresponds to the first
643                 // character after the label.
644                 pos_type sep = 0;
645                 if (style.labeltype != LABEL_NO_LABEL && style.docbookitemlabeltag() != "NONE") {
646                         if (style.labeltype == LABEL_MANUAL) {
647                                 // Only variablelist gets here (or similar items defined as an extension in the layout).
648                                 openTag(xs, style.docbookitemlabeltag(), style.docbookitemlabelattr(), style.docbookitemlabeltagtype());
649                                 sep = 1 + par->firstWordDocBook(xs, runparams);
650                                 closeTag(xs, style.docbookitemlabeltag(), style.docbookitemlabeltagtype());
651                         } else {
652                                 // Usual cases: maybe there is something specified at the layout level. Highly unlikely, though.
653                                 docstring const lbl = par->params().labelString();
654
655                                 if (!lbl.empty()) {
656                                         openTag(xs, style.docbookitemlabeltag(), style.docbookitemlabelattr(), style.docbookitemlabeltagtype());
657                                         xs << lbl;
658                                         closeTag(xs, style.docbookitemlabeltag(), style.docbookitemlabeltagtype());
659                                 }
660                         }
661                 }
662
663                 // Open the item (after the wrapper and the label).
664                 openTag(xs, style.docbookitemtag(), style.docbookitemattr(), style.docbookitemtagtype());
665
666                 // Generate the content of the item.
667                 if (sep < par->size()) {
668                         auto pars = par->simpleDocBookOnePar(buf, runparams,
669                                                              text.outerFont(std::distance(text.paragraphs().begin(), par)), sep);
670                         for (auto &p : pars) {
671                                 openTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnerattr(),
672                                         par->layout().docbookiteminnertagtype());
673                                 xs << XMLStream::ESCAPE_NONE << p;
674                                 closeTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnertagtype());
675                         }
676                 } else {
677                         // DocBook doesn't like emptiness.
678                         compTag(xs, par->layout().docbookiteminnertag(), par->layout().docbookiteminnerattr(),
679                                 par->layout().docbookiteminnertagtype());
680                 }
681
682                 // If the next item is deeper, it must go entirely within this item (do it recursively).
683                 // By construction, with findEndOfEnvironment, depth can only stay constant or increase, never decrease.
684                 depth_type currentDepth = par->getDepth();
685                 ++par;
686                 while (par != envend && par->getDepth() != currentDepth)
687                         par = makeAny(text, buf, xs, runparams, par);
688                 // Usually, this loop only makes one iteration, except in complex scenarios, like an item with a paragraph,
689                 // a list, and another paragraph; or an item with two types of list (itemise then enumerate, for instance).
690
691                 // Close the item.
692                 closeTag(xs, style.docbookitemtag(), style.docbookitemtagtype());
693                 closeTag(xs, style.docbookitemwrappertag(), style.docbookitemwrappertagtype());
694         }
695
696         // Close this environment in exactly the same way as it was opened.
697         closeTag(xs, envstyle.docbooktag(), envstyle.docbooktagtype());
698         closeTag(xs, envstyle.docbookwrappertag(), envstyle.docbookwrappertagtype());
699
700         return envend;
701 }
702
703
704 void makeCommand(
705                 Text const & text,
706                 Buffer const & buf,
707                 XMLStream & xs,
708                 OutputParams const & runparams,
709                 ParagraphList::const_iterator const & par)
710 {
711         // Unlike XHTML, no need for labels, as they are handled by DocBook tags.
712         auto const begin = text.paragraphs().begin();
713         auto const end = text.paragraphs().end();
714         auto nextpar = par;
715         ++nextpar;
716
717         // Generate this command.
718         auto prevpar = text.paragraphs().getParagraphBefore(par);
719         openParTag(xs, &*par, prevpar);
720
721         auto pars = par->simpleDocBookOnePar(buf, runparams,text.outerFont(distance(begin, par)));
722         for (auto & parXML : pars)
723                 // TODO: decide what to do with openParTag/closeParTag in new lines.
724                 xs << XMLStream::ESCAPE_NONE << parXML;
725
726         closeParTag(xs, &*par, (nextpar != end) ? &*nextpar : nullptr);
727 }
728
729
730 bool isLayoutSectioning(Layout const & lay)
731 {
732         if (lay.docbooksection()) // Special case: some DocBook styles must be handled as sections.
733                 return true;
734         else if (lay.category() == from_utf8("Sectioning") || lay.docbooktag() == "section") // Generic case.
735                 return lay.toclevel != Layout::NOT_IN_TOC;
736         return false;
737 }
738
739
740 bool isLayoutSectioningOrSimilar(Layout const & lay)
741 {
742         return isLayoutSectioning(lay) || lay.docbooktag() == "bridgehead";
743 }
744
745
746 using DocBookDocumentSectioning = tuple<bool, pit_type>;
747
748
749 struct DocBookInfoTag
750 {
751         const set<pit_type> shouldBeInInfo;
752         const set<pit_type> mustBeInInfo; // With the notable exception of the abstract!
753         const set<pit_type> abstract;
754         const bool abstractLayout;
755         pit_type bpit;
756         pit_type epit;
757
758         DocBookInfoTag(const set<pit_type> & shouldBeInInfo, const set<pit_type> & mustBeInInfo,
759                                    const set<pit_type> & abstract, bool abstractLayout, pit_type bpit, pit_type epit) :
760                                    shouldBeInInfo(shouldBeInInfo), mustBeInInfo(mustBeInInfo), abstract(abstract),
761                                    abstractLayout(abstractLayout), bpit(bpit), epit(epit) {}
762 };
763
764
765 DocBookDocumentSectioning hasDocumentSectioning(ParagraphList const &paragraphs, pit_type bpit, pit_type const epit) {
766         bool documentHasSections = false;
767
768         while (bpit < epit) {
769                 Layout const &style = paragraphs[bpit].layout();
770                 documentHasSections |= isLayoutSectioningOrSimilar(style);
771
772                 if (documentHasSections)
773                         break;
774                 bpit += 1;
775         }
776         // Paragraphs before the first section: [ runparams.par_begin ; eppit )
777
778         return make_tuple(documentHasSections, bpit);
779 }
780
781
782 bool hasOnlyNotes(Paragraph const & par)
783 {
784         // Precondition: the paragraph is not empty. Otherwise, the function will always return true...
785         for (int i = 0; i < par.size(); ++i)
786                 // If you find something that is not an inset (like actual text) or an inset that is not a note,
787                 // return false.
788                 if (!par.isInset(i) || par.getInset(i)->lyxCode() != NOTE_CODE)
789                         return false;
790
791         // An empty paragraph may still require some output.
792         if (par.layout().docbooksection())
793                 return false;
794
795         // There should be really no content here.
796         return true;
797 }
798
799
800 DocBookInfoTag getParagraphsWithInfo(ParagraphList const &paragraphs,
801                                                                          pit_type bpit, pit_type const epit,
802                                                                          // Typically, bpit is the beginning of the document and epit the end of the
803                                                                          // document *or* the first section.
804                                                                          bool documentHasSections,
805                                                                          bool detectUnlayoutedAbstract
806                                                                          // Whether paragraphs with no specific layout should be detected as abstracts.
807                                                                          // For inner sections, an abstract should only be detected if it has a specific
808                                                                          // layout. For others, anything that might look like an abstract should be sought.
809                                                                          ) {
810         set<pit_type> shouldBeInInfo;
811         set<pit_type> mustBeInInfo;
812         set<pit_type> abstractWithLayout;
813         set<pit_type> abstractNoLayout;
814
815         // Find the first non empty paragraph by mutating bpit.
816         while (bpit < epit) {
817                 Paragraph const &par = paragraphs[bpit];
818                 if (par.empty() || hasOnlyNotes(par))
819                         bpit += 1;
820                 else
821                         break;
822         }
823
824         // Traverse everything that might belong to <info>.
825         bool hasAbstractLayout = false;
826         pit_type cpit = bpit;
827         for (; cpit < epit; ++cpit) {
828                 // Skip paragraphs that don't generate anything in DocBook.
829                 Paragraph const & par = paragraphs[cpit];
830                 Layout const &style = par.layout();
831                 if (hasOnlyNotes(par))
832                         continue;
833
834                 // There should never be any section here, except for the first paragraph (a title can be part of <info>).
835                 // (Just a sanity check: if this fails, this function could end up processing the whole document.)
836                 if (cpit != bpit && isLayoutSectioningOrSimilar(par.layout())) {
837                         LYXERR0("Assertion failed: section found in potential <info> paragraphs.");
838                         break;
839                 }
840
841                 // If this is marked as an abstract by the layout, put it in the right set.
842                 if (style.docbookabstract()) {
843                         hasAbstractLayout = true;
844                         abstractWithLayout.emplace(cpit);
845                         continue;
846                 }
847
848                 // Based on layout information, store this paragraph in one set: should be in <info>, must be,
849                 // or abstract (either because of layout or of position).
850                 if (style.docbookininfo() == "always")
851                         mustBeInInfo.emplace(cpit);
852                 else if (style.docbookininfo() == "maybe")
853                         shouldBeInInfo.emplace(cpit);
854                 else if (documentHasSections && !hasAbstractLayout && detectUnlayoutedAbstract &&
855                                 (style.docbooktag() == "NONE" || style.docbooktag() == "para") &&
856                                 style.docbookwrappertag() == "NONE")
857                         // In this case, it is very likely that style.docbookininfo() == "never"! Be extra careful
858                         // about anything that gets caught here.
859                         abstractNoLayout.emplace(cpit);
860                 else // This should definitely not be in <info>.
861                         break;
862         }
863         // Now, cpit points to the first paragraph that no more has things that could go in <info>.
864         // bpit is the beginning of the <info> part.
865
866         return DocBookInfoTag(shouldBeInInfo, mustBeInInfo,
867                                               hasAbstractLayout ? abstractWithLayout : abstractNoLayout,
868                                               hasAbstractLayout, bpit, cpit);
869 }
870
871 } // end anonymous namespace
872
873
874 ParagraphList::const_iterator makeAny(Text const &text,
875                                       Buffer const &buf,
876                                       XMLStream &xs,
877                                       OutputParams const &runparams,
878                                       ParagraphList::const_iterator par)
879 {
880         switch (par->layout().latextype) {
881         case LATEX_COMMAND:
882                 makeCommand(text, buf, xs, runparams, par);
883                 break;
884         case LATEX_ENVIRONMENT:
885                 makeEnvironment(text, buf, xs, runparams, par);
886                 break;
887         case LATEX_LIST_ENVIRONMENT:
888         case LATEX_ITEM_ENVIRONMENT:
889                 // Only case when makeAny() might consume more than one paragraph.
890                 return makeListEnvironment(text, buf, xs, runparams, par);
891         case LATEX_PARAGRAPH:
892                 makeParagraph(text, buf, xs, runparams, par);
893                 break;
894         case LATEX_BIB_ENVIRONMENT:
895                 makeBibliography(text, buf, xs, runparams, par);
896                 break;
897         }
898         ++par;
899         return par;
900 }
901
902
903 xml::FontTag docbookStartFontTag(xml::FontTypes type)
904 {
905         return xml::FontTag(from_utf8(fontToDocBookTag(type)), from_utf8(fontToAttribute(type)), type);
906 }
907
908
909 xml::EndFontTag docbookEndFontTag(xml::FontTypes type)
910 {
911         return xml::EndFontTag(from_utf8(fontToDocBookTag(type)), type);
912 }
913
914
915 void outputDocBookInfo(
916                 Text const & text,
917                 Buffer const & buf,
918                 XMLStream & xs,
919                 OutputParams const & runparams,
920                 ParagraphList const & paragraphs,
921                 DocBookInfoTag const & info)
922 {
923         // Perform an additional check on the abstract. Sometimes, there are many paragraphs that should go
924         // into the abstract, but none generates actual content. Thus, first generate to a temporary stream,
925         // then only create the <abstract> tag if these paragraphs generate some content.
926         // This check must be performed *before* a decision on whether or not to output <info> is made.
927         bool hasAbstract = !info.abstract.empty();
928         docstring abstract;
929         if (hasAbstract) {
930                 // Generate the abstract XML into a string before further checks.
931                 // Usually, makeAny only generates one paragraph at a time. However, for the specific case of lists, it might
932                 // generate more than one paragraph, as indicated in the return value.
933                 odocstringstream os2;
934                 XMLStream xs2(os2);
935
936                 set<pit_type> doneParas;
937                 for (auto const & p : info.abstract) {
938                         if (doneParas.find(p) == doneParas.end()) {
939                                 auto oldPar = paragraphs.iterator_at(p);
940                                 auto newPar = makeAny(text, buf, xs2, runparams, oldPar);
941
942                                 // Insert the indices of all the paragraphs that were just generated (typically, one).
943                                 // **Make the hypothesis that, when an abstract has a list, all its items are consecutive.**
944                                 pit_type id = p;
945                                 while (oldPar != newPar) {
946                                         doneParas.emplace(id);
947                                         ++oldPar;
948                                         ++id;
949                                 }
950                         }
951                 }
952
953                 // Actually output the abstract if there is something to do. Don't count line feeds or spaces in this,
954                 // even though they must be properly output if there is some abstract.
955                 abstract = os2.str();
956                 docstring cleaned = abstract;
957                 cleaned.erase(std::remove_if(cleaned.begin(), cleaned.end(), lyx::isSpace), cleaned.end());
958
959                 // Nothing? Then there is no abstract!
960                 if (cleaned.empty())
961                         hasAbstract = false;
962         }
963
964         // The abstract must go in <info>. Otherwise, decide whether to open <info> based on the layouts.
965         bool needInfo = !info.mustBeInInfo.empty() || hasAbstract;
966
967         // Start the <info> tag if required.
968         if (needInfo) {
969                 xs.startDivision(false);
970                 xs << xml::StartTag("info");
971                 xs << xml::CR();
972         }
973
974         // Output the elements that should go in <info>, before and after the abstract.
975         for (auto pit : info.shouldBeInInfo) // Typically, the title: these elements are so important and ubiquitous
976                 // that mandating a wrapper like <info> would repel users. Thus, generate them first.
977                 makeAny(text, buf, xs, runparams, paragraphs.iterator_at(pit));
978         for (auto pit : info.mustBeInInfo)
979                 makeAny(text, buf, xs, runparams, paragraphs.iterator_at(pit));
980
981         // If there is no title, generate one (required for the document to be valid).
982         // This code is called for the main document, for table cells, etc., so be precise in this condition.
983         if (text.isMainText() && info.shouldBeInInfo.empty() && !runparams.inInclude) {
984                 xs << xml::StartTag("title");
985                 xs << "Untitled Document";
986                 xs << xml::EndTag("title");
987                 xs << xml::CR();
988         }
989
990         // Always output the abstract as the last item of the <info>, as it requires special treatment (especially if
991         // it contains several paragraphs that are empty).
992         if (hasAbstract) {
993                 if (info.abstractLayout) {
994                         xs << XMLStream::ESCAPE_NONE << abstract;
995                         xs << xml::CR();
996                 } else {
997                         string tag = paragraphs[*info.abstract.begin()].layout().docbookforceabstracttag();
998                         if (tag == "NONE")
999                                 tag = "abstract";
1000
1001                         if (!xs.isLastTagCR())
1002                                 xs << xml::CR();
1003
1004                         xs << xml::StartTag(tag);
1005                         xs << xml::CR();
1006                         xs << XMLStream::ESCAPE_NONE << abstract;
1007                         xs << xml::EndTag(tag);
1008                         xs << xml::CR();
1009                 }
1010         }
1011
1012         // End the <info> tag if it was started.
1013         if (needInfo) {
1014                 if (!xs.isLastTagCR())
1015                         xs << xml::CR();
1016
1017                 xs << xml::EndTag("info");
1018                 xs << xml::CR();
1019                 xs.endDivision();
1020         }
1021 }
1022
1023
1024 void docbookSimpleAllParagraphs(
1025                 Text const & text,
1026                 Buffer const & buf,
1027                 XMLStream & xs,
1028                 OutputParams const & runparams)
1029 {
1030         // Handle the given text, supposing it has no sections (i.e. a "simple" text). The input may vary in length
1031         // between a single paragraph to a whole document.
1032         pit_type const bpit = runparams.par_begin;
1033         pit_type const epit = runparams.par_end;
1034         ParagraphList const &paragraphs = text.paragraphs();
1035
1036         // First, the <info> tag.
1037         DocBookInfoTag info = getParagraphsWithInfo(paragraphs, bpit, epit, false, true);
1038         outputDocBookInfo(text, buf, xs, runparams, paragraphs, info);
1039
1040         // Then, the content. It starts where the <info> ends.
1041         auto par = paragraphs.iterator_at(info.epit);
1042         auto end = paragraphs.iterator_at(epit);
1043         while (par != end) {
1044                 if (!hasOnlyNotes(*par))
1045                         par = makeAny(text, buf, xs, runparams, par);
1046                 else
1047                         ++par;
1048         }
1049 }
1050
1051
1052 void docbookParagraphs(Text const &text,
1053                                            Buffer const &buf,
1054                                            XMLStream &xs,
1055                                            OutputParams const &runparams) {
1056         ParagraphList const &paragraphs = text.paragraphs();
1057         if (runparams.par_begin == runparams.par_end) {
1058                 runparams.par_begin = 0;
1059                 runparams.par_end = paragraphs.size();
1060         }
1061         pit_type bpit = runparams.par_begin;
1062         pit_type const epit = runparams.par_end;
1063         LASSERT(bpit < epit,
1064                         {
1065                                 xs << XMLStream::ESCAPE_NONE << "<!-- DocBook output error! -->\n";
1066                                 return;
1067                         });
1068
1069         std::stack<std::pair<int, string>> headerLevels; // Used to determine when to open/close sections: store the depth
1070         // of the section and the tag that was used to open it.
1071
1072         // Detect whether the document contains sections. If there are no sections, treatment is largely simplified.
1073         // In particular, there can't be an abstract, unless it is manually marked.
1074         bool documentHasSections;
1075         pit_type eppit;
1076         tie(documentHasSections, eppit) = hasDocumentSectioning(paragraphs, bpit, epit);
1077
1078         // Deal with "simple" documents, i.e. those without sections.
1079         if (!documentHasSections) {
1080                 docbookSimpleAllParagraphs(text, buf, xs, runparams);
1081                 return;
1082         }
1083
1084         // Output the first <info> tag (or just the title).
1085         DocBookInfoTag info = getParagraphsWithInfo(paragraphs, bpit, eppit, true, true);
1086         outputDocBookInfo(text, buf, xs, runparams, paragraphs, info);
1087         bpit = info.epit;
1088
1089         // Then, iterate through the paragraphs of this document.
1090         bool currentlyInAppendix = false;
1091
1092         auto par = text.paragraphs().iterator_at(bpit);
1093         auto end = text.paragraphs().iterator_at(epit);
1094         while (par != end) {
1095                 OutputParams ourparams = runparams;
1096
1097                 if (par->params().startOfAppendix())
1098                         currentlyInAppendix = true;
1099                 if (hasOnlyNotes(*par)) {
1100                         ++par;
1101                         continue;
1102                 }
1103
1104                 Layout const &style = par->layout();
1105
1106                 // Think about adding <section> and/or </section>s.
1107                 if (isLayoutSectioning(style)) {
1108                         int level = style.toclevel;
1109
1110                         // Need to close a previous section if it has the same level or a higher one (close <section> if opening a
1111                         // <h2> after a <h2>, <h3>, <h4>, <h5> or <h6>). More examples:
1112                         //   - current: h2; back: h1; do not close any <section>
1113                         //   - current: h1; back: h2; close two <section> (first the <h2>, then the <h1>, so a new <h1> can come)
1114                         while (!headerLevels.empty() && level <= headerLevels.top().first) {
1115                                 // Output the tag only if it corresponds to a legit section.
1116                                 int stackLevel = headerLevels.top().first;
1117                                 if (stackLevel != Layout::NOT_IN_TOC) {
1118                                         xs << xml::EndTag(headerLevels.top().second);
1119                                         xs << xml::CR();
1120                                 }
1121                                 headerLevels.pop();
1122                         }
1123
1124                         // Open the new section: first push it onto the stack, then output it in DocBook.
1125                         string sectionTag = (currentlyInAppendix && style.docbooksectiontag() == "chapter") ?
1126                                                                 "appendix" : style.docbooksectiontag();
1127                         headerLevels.push(std::make_pair(level, sectionTag));
1128
1129                         // Some sectioning-like elements should not be output (such as FrontMatter).
1130                         if (level != Layout::NOT_IN_TOC) {
1131                                 // Look for a label in the title, i.e. a InsetLabel as a child.
1132                                 docstring id = docstring();
1133                                 for (pos_type i = 0; i < par->size(); ++i) {
1134                                         Inset const *inset = par->getInset(i);
1135                                         if (inset) {
1136                                                 if (auto label = dynamic_cast<InsetLabel const *>(inset)) {
1137                                                         // Generate the attributes for the section if need be.
1138                                                         id += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
1139
1140                                                         // Don't output the ID as a DocBook <anchor>.
1141                                                         ourparams.docbook_anchors_to_ignore.emplace(label->screenLabel());
1142
1143                                                         // Cannot have multiple IDs per tag. If there is another ID inset in the document, it will
1144                                                         // be output as a DocBook anchor.
1145                                                         break;
1146                                                 }
1147                                         }
1148                                 }
1149
1150                                 // Write the open tag for this section.
1151                                 docstring attrs;
1152                                 if (!id.empty())
1153                                         attrs = id;
1154                                 xs << xml::StartTag(sectionTag, attrs);
1155                                 xs << xml::CR();
1156                         }
1157                 }
1158
1159                 // Close all sections before the bibliography.
1160                 // TODO: Only close all when the bibliography is at the end of the document? Or force to output the bibliography at the end of the document? Or don't care (as allowed by DocBook)?
1161                 if (!par->insetList().empty()) {
1162                         Inset const *firstInset = par->getInset(0);
1163                         if (firstInset && (firstInset->lyxCode() == BIBITEM_CODE || firstInset->lyxCode() == BIBTEX_CODE)) {
1164                                 while (!headerLevels.empty()) {
1165                                         int level = headerLevels.top().first;
1166                                         docstring tag = from_utf8("</" + headerLevels.top().second + ">");
1167                                         headerLevels.pop();
1168
1169                                         // Output the tag only if it corresponds to a legit section.
1170                                         if (level != Layout::NOT_IN_TOC) {
1171                                                 xs << XMLStream::ESCAPE_NONE << tag;
1172                                                 xs << xml::CR();
1173                                         }
1174                                 }
1175                         }
1176                 }
1177
1178                 // Generate the <info> tag if a section was just opened.
1179                 // Some sections may require abstracts (mostly parts, in books: DocBookForceAbstractTag will not be NONE),
1180                 // others can still have an abstract (it must be detected so that it can be output at the right place).
1181                 // TODO: docbookforceabstracttag is a bit contrived here, but it does the job. Having another field just for this would be cleaner, but that's just for <part> and <partintro>, so it's probably not worth the effort.
1182                 if (isLayoutSectioning(style)) {
1183                         // This abstract may be found between the next paragraph and the next title.
1184                         pit_type cpit = std::distance(text.paragraphs().begin(), par);
1185                         pit_type ppit = std::get<1>(hasDocumentSectioning(paragraphs, cpit + 1L, epit));
1186
1187                         // Generate this abstract (this code corresponds to parts of outputDocBookInfo).
1188                         DocBookInfoTag secInfo = getParagraphsWithInfo(paragraphs, cpit, ppit, true,
1189                                                                                                   style.docbookforceabstracttag() != "NONE");
1190
1191                         if (!secInfo.mustBeInInfo.empty() || !secInfo.shouldBeInInfo.empty() || !secInfo.abstract.empty()) {
1192                                 // Generate the <info>, if required. If DocBookForceAbstractTag != NONE, this abstract will not be in
1193                                 // <info>, unlike other ("standard") abstracts.
1194                                 bool hasStandardAbstract = !secInfo.abstract.empty() && style.docbookforceabstracttag() == "NONE";
1195                                 bool needInfo = !secInfo.mustBeInInfo.empty() || hasStandardAbstract;
1196
1197                                 if (needInfo) {
1198                                         xs.startDivision(false);
1199                                         xs << xml::StartTag("info");
1200                                         xs << xml::CR();
1201                                 }
1202
1203                                 // Output the elements that should go in <info>, before and after the abstract.
1204                                 for (auto pit : secInfo.shouldBeInInfo) // Typically, the title: these elements are so important and ubiquitous
1205                                         // that mandating a wrapper like <info> would repel users. Thus, generate them first.
1206                                         makeAny(text, buf, xs, ourparams, paragraphs.iterator_at(pit));
1207                                 for (auto pit : secInfo.mustBeInInfo)
1208                                         makeAny(text, buf, xs, ourparams, paragraphs.iterator_at(pit));
1209
1210                                 // Deal with the abstract in <info> if it is standard (i.e. its tag is <abstract>).
1211                                 if (!secInfo.abstract.empty() && hasStandardAbstract) {
1212                                         if (!secInfo.abstractLayout) {
1213                                                 xs << xml::StartTag("abstract");
1214                                                 xs << xml::CR();
1215                                         }
1216
1217                                         for (auto const &p : secInfo.abstract)
1218                                                 makeAny(text, buf, xs, ourparams, paragraphs.iterator_at(p));
1219
1220                                         if (!secInfo.abstractLayout) {
1221                                                 xs << xml::EndTag("abstract");
1222                                                 xs << xml::CR();
1223                                         }
1224                                 }
1225
1226                                 // End the <info> tag if it was started.
1227                                 if (needInfo) {
1228                                         if (!xs.isLastTagCR())
1229                                                 xs << xml::CR();
1230
1231                                         xs << xml::EndTag("info");
1232                                         xs << xml::CR();
1233                                         xs.endDivision();
1234                                 }
1235
1236                                 // Deal with the abstract outside <info> if it is not standard (i.e. its tag is layout-defined).
1237                                 if (!secInfo.abstract.empty() && !hasStandardAbstract) {
1238                                         // Assert: style.docbookforceabstracttag() != NONE.
1239                                         xs << xml::StartTag(style.docbookforceabstracttag());
1240                                         xs << xml::CR();
1241                                         for (auto const &p : secInfo.abstract)
1242                                                 makeAny(text, buf, xs, ourparams, paragraphs.iterator_at(p));
1243                                         xs << xml::EndTag(style.docbookforceabstracttag());
1244                                         xs << xml::CR();
1245                                 }
1246
1247                                 // Skip all the text that has just been generated.
1248                                 par = paragraphs.iterator_at(secInfo.epit);
1249                         } else {
1250                                 // No <info> tag to generate, proceed as for normal paragraphs.
1251                                 par = makeAny(text, buf, xs, ourparams, par);
1252                         }
1253                 } else {
1254                         // Generate this paragraph, as it has nothing special.
1255                         par = makeAny(text, buf, xs, ourparams, par);
1256                 }
1257         }
1258
1259         // If need be, close <section>s, but only at the end of the document (otherwise, dealt with at the beginning
1260         // of the loop).
1261         while (!headerLevels.empty() && headerLevels.top().first > Layout::NOT_IN_TOC) {
1262                 docstring tag = from_utf8("</" + headerLevels.top().second + ">");
1263                 headerLevels.pop();
1264                 xs << XMLStream::ESCAPE_NONE << tag;
1265                 xs << xml::CR();
1266         }
1267 }
1268
1269 } // namespace lyx