]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
Move Lexer to support/ directory (and lyx::support namespace)
[lyx.git] / src / insets / InsetFloat.cpp
1 /**
2  * \file InsetFloat.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Jürgen Spitzmüller
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "InsetFloat.h"
16
17 #include "InsetBox.h"
18 #include "InsetCaption.h"
19 #include "InsetGraphics.h"
20 #include "InsetLabel.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "Counters.h"
26 #include "Cursor.h"
27 #include "DispatchResult.h"
28 #include "Floating.h"
29 #include "FloatList.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
32 #include "LaTeXFeatures.h"
33 #include "xml.h"
34 #include "output_docbook.h"
35 #include "output_xhtml.h"
36 #include "ParIterator.h"
37 #include "TexRow.h"
38 #include "texstream.h"
39 #include "TextClass.h"
40 #include "InsetList.h"
41
42 #include "support/debug.h"
43 #include "support/docstream.h"
44 #include "support/gettext.h"
45 #include "support/Lexer.h"
46 #include "support/lstrings.h"
47
48 #include "frontends/Application.h"
49
50 using namespace std;
51 using namespace lyx::support;
52
53
54 namespace lyx {
55
56 // With this inset it will be possible to support the latex package
57 // float.sty, and I am sure that with this and some additional support
58 // classes we can support similar functionality in other formats
59 // (read DocBook).
60 // By using float.sty we will have the same handling for all floats, both
61 // for those already in existence (table and figure) and all user created
62 // ones¹. So suddenly we give the users the possibility of creating new
63 // kinds of floats on the fly. (and with a uniform look)
64 //
65 // API to float.sty:
66 //   \newfloat{type}{placement}{ext}[within]
67 //     type      - The "type" of the new class of floats, like program or
68 //                 algorithm. After the appropriate \newfloat, commands
69 //                 such as \begin{program} or \end{algorithm*} will be
70 //                 available.
71 //     placement - The default placement for the given class of floats.
72 //                 They are like in standard LaTeX: t, b, p and h for top,
73 //                 bottom, page, and here, respectively. On top of that
74 //                 there is a new type, H, which does not really correspond
75 //                 to a float, since it means: put it "here" and nowhere else.
76 //                 Note, however that the H specifier is special and, because
77 //                 of implementation details cannot be used in the second
78 //                 argument of \newfloat.
79 //     ext       - The file name extension of an auxiliary file for the list
80 //                 of figures (or whatever). LaTeX writes the captions to
81 //                 this file.
82 //     within    - This (optional) argument determines whether floats of this
83 //                 class will be numbered within some sectional unit of the
84 //                 document. For example, if within is equal to chapter, the
85 //                 floats will be numbered within chapters.
86 //   \floatstyle{style}
87 //     style -  plain, boxed, ruled
88 //   \floatname{float}{floatname}
89 //     float     -
90 //     floatname -
91 //   \floatplacement{float}{placement}
92 //     float     -
93 //     placement -
94 //   \restylefloat{float}
95 //     float -
96 //   \listof{type}{title}
97 //     title -
98
99 // ¹ the algorithm float is defined using the float.sty package. Like this
100 //   \floatstyle{ruled}
101 //   \newfloat{algorithm}{htbp}{loa}[<sect>]
102 //   \floatname{algorithm}{Algorithm}
103 //
104 // The intention is that floats should be definable from two places:
105 //          - layout files
106 //          - the "gui" (i.e. by the user)
107 //
108 // From layout files.
109 // This should only be done for floats defined in a documentclass and that
110 // does not need any additional packages. The two most known floats in this
111 // category is "table" and "figure". Floats defined in layout files are only
112 // stored in lyx files if the user modifies them.
113 //
114 // By the user.
115 // There should be a gui dialog (and also a collection of lyxfuncs) where
116 // the user can modify existing floats and/or create new ones.
117 //
118 // The individual floats will also have some settable
119 // variables: wide and placement.
120 //
121 // Lgb
122
123 //FIXME: why do we set in stone the type here?
124 InsetFloat::InsetFloat(Buffer * buf, string const & params_str)
125         : InsetCaptionable(buf)
126 {
127         string2params(params_str, params_);
128         setCaptionType(params_.type);
129 }
130
131
132 // Enforce equality of float type and caption type.
133 void InsetFloat::setCaptionType(std::string const & type)
134 {
135         InsetCaptionable::setCaptionType(type);
136         params_.type = captionType();
137         // check if the float type exists
138         if (buffer().params().documentClass().floats().typeExist(params_.type))
139                 setNewLabel();
140         else
141                 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
142 }
143
144
145 docstring InsetFloat::layoutName() const
146 {
147         return "Float:" + from_utf8(params_.type);
148 }
149
150
151 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
152 {
153         if (isOpen(bv))
154                 return InsetCaptionable::toolTip(bv, x, y);
155
156         OutputParams rp(&buffer().params().encoding());
157         return getCaptionText(rp);
158 }
159
160
161 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
162 {
163         switch (cmd.action()) {
164
165         case LFUN_INSET_MODIFY: {
166                 if (!buffer().params().documentClass().floats().typeExist(cmd.getArg(0))) {
167                         // not for us: pass further.
168                         cur.undispatched();
169                         break;
170                 }
171                 InsetFloatParams params;
172                 string2params(to_utf8(cmd.argument()), params);
173                 cur.recordUndoInset(this);
174
175                 // placement, wide and sideways are not used for subfloats
176                 if (!params_.subfloat) {
177                         params_.placement = params.placement;
178                         params_.wide      = params.wide;
179                         params_.sideways  = params.sideways;
180                 }
181                 params_.alignment  = params.alignment;
182                 setNewLabel();
183                 if (params_.type != params.type)
184                         setCaptionType(params.type);
185                 // what we really want here is a TOC update, but that means
186                 // a full buffer update
187                 cur.forceBufferUpdate();
188                 break;
189         }
190
191         case LFUN_INSET_DIALOG_UPDATE: {
192                 cur.bv().updateDialog("float", params2string(params()));
193                 break;
194         }
195
196         default:
197                 InsetCaptionable::doDispatch(cur, cmd);
198                 break;
199         }
200 }
201
202
203 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
204                 FuncStatus & flag) const
205 {
206         switch (cmd.action()) {
207
208         case LFUN_INSET_MODIFY:
209                 if (!buffer().params().documentClass().floats().typeExist(cmd.getArg(0)))
210                         return Inset::getStatus(cur, cmd, flag);
211         // fall through
212         case LFUN_INSET_DIALOG_UPDATE:
213                 flag.setEnabled(true);
214                 return true;
215
216         case LFUN_INSET_SETTINGS:
217                 if (InsetCaptionable::getStatus(cur, cmd, flag)) {
218                         flag.setEnabled(flag.enabled() && !params_.subfloat);
219                         return true;
220                 } else
221                         return false;
222
223         case LFUN_NEWLINE_INSERT:
224                 if (params_.subfloat) {
225                         flag.setEnabled(false);
226                         return true;
227                 }
228                 // no subfloat:
229                 // fall through
230
231         default:
232                 return InsetCaptionable::getStatus(cur, cmd, flag);
233         }
234 }
235
236
237 bool InsetFloat::hasSubCaptions(ParIterator const & it) const
238 {
239         return (it.innerInsetOfType(FLOAT_CODE) || it.innerInsetOfType(WRAP_CODE));
240 }
241
242
243 string InsetFloat::getAlignment() const
244 {
245         string alignment;
246         string const buf_alignment = buffer().params().float_alignment;
247         if (params_.alignment == "document"
248             && !buf_alignment.empty()) {
249                 alignment = buf_alignment;
250         } else if (!params_.alignment.empty()
251                    && params_.alignment != "class"
252                    && params_.alignment != "document") {
253                 alignment = params_.alignment;
254         }
255         return alignment;
256 }
257
258
259 CtObject InsetFloat::getCtObject(OutputParams const &) const
260 {
261         return CtObject::OmitObject;
262 }
263
264
265 LyXAlignment InsetFloat::contentAlignment() const
266 {
267         LyXAlignment align = LYX_ALIGN_NONE;
268         string alignment = getAlignment();
269         if (alignment == "left")
270                 align = LYX_ALIGN_LEFT;
271         else if (alignment == "center")
272                 align = LYX_ALIGN_CENTER;
273         else if (alignment == "right")
274                 align = LYX_ALIGN_RIGHT;
275
276         return align;
277 }
278
279
280 void InsetFloatParams::write(ostream & os) const
281 {
282         if (type.empty()) {
283                 // Better this than creating a parse error. This in fact happens in the
284                 // parameters dialog via InsetFloatParams::params2string.
285                 os << "senseless" << '\n';
286         } else
287                 os << type << '\n';
288
289         if (!placement.empty())
290                 os << "placement " << placement << "\n";
291         if (!alignment.empty())
292                 os << "alignment " << alignment << "\n";
293
294         if (wide)
295                 os << "wide true\n";
296         else
297                 os << "wide false\n";
298
299         if (sideways)
300                 os << "sideways true\n";
301         else
302                 os << "sideways false\n";
303 }
304
305
306 void InsetFloatParams::read(Lexer & lex)
307 {
308         lex.setContext("InsetFloatParams::read");
309         lex >> type;
310         if (lex.checkFor("placement"))
311                 lex >> placement;
312         if (lex.checkFor("alignment"))
313                 lex >> alignment;
314         lex >> "wide" >> wide;
315         lex >> "sideways" >> sideways;
316 }
317
318
319 void InsetFloat::write(ostream & os) const
320 {
321         os << "Float ";
322         params_.write(os);
323         InsetCaptionable::write(os);
324 }
325
326
327 void InsetFloat::read(Lexer & lex)
328 {
329         params_.read(lex);
330         InsetCaptionable::read(lex);
331         setCaptionType(params_.type);
332 }
333
334
335 void InsetFloat::validate(LaTeXFeatures & features) const
336 {
337         if (support::contains(params_.placement, 'H'))
338                 features.require("float");
339
340         if (params_.sideways)
341                 features.require("rotfloat");
342
343         if (features.inFloat())
344                 features.require("subfig");
345
346         if (features.inDeletedInset()) {
347                 features.require("tikz");
348                 features.require("ct-tikz-object-sout");
349         }
350
351         features.useFloat(params_.type, features.inFloat());
352         features.inFloat(true);
353         InsetCaptionable::validate(features);
354         features.inFloat(false);
355 }
356
357
358 docstring InsetFloat::xhtml(XMLStream & xs, OutputParams const & rp) const
359 {
360         FloatList const & floats = buffer().params().documentClass().floats();
361         Floating const & ftype = floats.getType(params_.type);
362         string const & htmltype = ftype.htmlTag();
363         string const & attr = ftype.htmlAttrib();
364
365         odocstringstream ods;
366         XMLStream newxs(ods);
367         newxs << xml::StartTag(htmltype, attr);
368         InsetText::XHTMLOptions const opts =
369                 InsetText::WriteLabel | InsetText::WriteInnerTag;
370         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
371         newxs << xml::EndTag(htmltype);
372
373         if (rp.inFloat == OutputParams::NONFLOAT) {
374                 // In this case, this float needs to be deferred, but we'll put it
375                 // before anything the text itself deferred.
376                 deferred = ods.str() + '\n' + deferred;
377         } else {
378                 // In this case, the whole thing is already being deferred, so
379                 // we can write to the stream.
380                 // Note that things will already have been escaped, so we do not
381                 // want to escape them again.
382                 xs << XMLStream::ESCAPE_NONE << ods.str();
383         }
384         return deferred;
385 }
386
387
388 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
389 {
390         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
391                 if (!paragraphs().empty() && !runparams_in.nice)
392                         // improve TexRow precision in non-nice mode
393                         os << safebreakln;
394
395                 if (runparams_in.moving_arg)
396                         os << "\\protect";
397                 os << "\\subfloat";
398
399                 OutputParams rp = runparams_in;
400                 rp.moving_arg = true;
401                 rp.inFloat = OutputParams::SUBFLOAT;
402                 os << getCaption(rp);
403                 os << '{';
404                 // The main argument is the contents of the float. This is not a moving argument.
405                 rp.moving_arg = false;
406                 InsetText::latex(os, rp);
407                 os << "}";
408
409                 return;
410         }
411         OutputParams runparams(runparams_in);
412         runparams.inFloat = OutputParams::MAINFLOAT;
413
414         FloatList const & floats = buffer().params().documentClass().floats();
415         string tmptype = params_.type;
416         if (params_.sideways && floats.allowsSideways(params_.type))
417                 tmptype = "sideways" + params_.type;
418         if (params_.wide && floats.allowsWide(params_.type)
419                 && (!params_.sideways ||
420                      params_.type == "figure" ||
421                      params_.type == "table"))
422                 tmptype += "*";
423         // Figure out the float placement to use.
424         // From lowest to highest:
425         // - float default placement
426         // - document wide default placement
427         // - specific float placement
428         string tmpplacement;
429         string const buf_placement = buffer().params().float_placement;
430         string const def_placement = floats.defaultPlacement(params_.type);
431         if (params_.placement == "document"
432             && !buf_placement.empty()
433             && buf_placement != def_placement) {
434                 tmpplacement = buf_placement;
435         } else if (!params_.placement.empty()
436                    && params_.placement != "document"
437                    && params_.placement != def_placement) {
438                 tmpplacement = params_.placement;
439         }
440
441         // Check if placement is allowed by this float
442         string const allowed_placement =
443                 floats.allowedPlacement(params_.type);
444         string placement;
445         string::const_iterator lit = tmpplacement.begin();
446         string::const_iterator end = tmpplacement.end();
447         for (; lit != end; ++lit) {
448                 if (contains(allowed_placement, *lit))
449                         placement += *lit;
450         }
451
452         // Force \begin{<floatname>} to appear in a new line.
453         os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
454         if (runparams.lastid != -1)
455                 os.texrow().start(runparams.lastid, runparams.lastpos);
456         // We only output placement if different from the def_placement.
457         // sidewaysfloats always use their own page,
458         // therefore don't output the p option that is always set
459         if (!placement.empty()
460             && (!params_.sideways || from_ascii(placement) != "p"))
461                 os << '[' << from_ascii(placement) << ']';
462         os << '\n';
463
464         if (runparams.inDeletedInset) {
465                 // This has to be done manually since we need it inside the float
466                 CtObject ctobject = runparams.ctObject;
467                 runparams.ctObject = CtObject::DisplayObject;
468                 Changes::latexMarkChange(os, buffer().params(), Change(Change::UNCHANGED),
469                                          Change(Change::DELETED), runparams);
470                 runparams.ctObject = ctobject;
471         }
472
473         string alignment = getAlignment();
474         if (alignment == "left")
475                 os << "\\raggedright" << breakln;
476         else if (alignment == "center")
477                 os << "\\centering" << breakln;
478         else if (alignment == "right")
479                 os << "\\raggedleft" << breakln;
480
481         InsetText::latex(os, runparams);
482
483         if (runparams.inDeletedInset)
484                 os << "}";
485
486         // Force \end{<floatname>} to appear in a new line.
487         os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
488 }
489
490
491 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
492 {
493         os << '[' << buffer().B_("float") << ' '
494                 << floatName(params_.type) << ":\n";
495         InsetText::plaintext(os, runparams, max_length);
496         os << "\n]";
497
498         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
499 }
500
501
502 std::vector<const InsetCollapsible *> findSubfiguresInParagraph(const Paragraph &par)
503 {
504
505         // Don't make the hypothesis that all subfigures are in the same paragraph.
506         // Similarly, there may be several subfigures in the same paragraph (most likely case, based on the documentation).
507         // Any box is considered as a subfigure, even though the most likely case is \minipage.
508         // Boxes are not required to make subfigures. The common root between InsetBox and InsetFLoat is InsetCollapsible.
509         std::vector<const InsetCollapsible *> subfigures;
510         for (pos_type pos = 0; pos < par.size(); ++pos) {
511                 const Inset *inset = par.getInset(pos);
512                 if (!inset)
513                         continue;
514                 if (const auto box = dynamic_cast<const InsetBox *>(inset))
515                         subfigures.push_back(box);
516                 else if (const auto fl = dynamic_cast<const InsetFloat *>(inset))
517                         subfigures.push_back(fl);
518         }
519         return subfigures;
520 }
521
522
523 /// Takes an unstructured subfigure container (typically, an InsetBox) and find the elements within:
524 /// actual content (image or table), maybe a caption, maybe a label.
525 std::tuple<InsetCode, const Inset *, const InsetCaption *, const InsetLabel *> docbookParseHopelessSubfigure(const InsetText * subfigure)
526 {
527         InsetCode type = NO_CODE;
528         const Inset * content = nullptr;
529         const InsetCaption * caption = nullptr;
530         const InsetLabel * label = nullptr;
531
532         for (const auto & it : subfigure->paragraphs()) {
533                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
534                         const Inset * inset = it.getInset(posIn);
535                         if (inset) {
536                                 switch (inset->lyxCode()) {
537                                         case GRAPHICS_CODE:
538                                         case TABULAR_CODE:
539                                                 if (!content) {
540                                                         content = inset;
541                                                         type = inset->lyxCode();
542                                                 }
543                                                 break;
544                                         case CAPTION_CODE:
545                                                 if (!caption) {
546                                                         caption = dynamic_cast<const InsetCaption *>(inset);
547
548                                                         // A label often hides in a caption. Make a simplified version of the main loop.
549                                                         if (!label) {
550                                                                 for (const auto &cit : caption->paragraphs()) {
551                                                                         for (pos_type cposIn = 0; cposIn < cit.size(); ++cposIn) {
552                                                                                 const Inset *cinset = cit.getInset(posIn);
553                                                                                 if (cinset && cinset->lyxCode() == LABEL_CODE) {
554                                                                                         label = dynamic_cast<const InsetLabel *>(cinset);
555                                                                                         break;
556                                                                                 }
557                                                                         }
558
559                                                                         if (label)
560                                                                                 break;
561                                                                 }
562                                                         }
563                                                 }
564                                                 break;
565                                         case LABEL_CODE:
566                                                 if (!label)
567                                                         label = dynamic_cast<const InsetLabel *>(inset);
568                                                 break;
569                                         default:
570                                                 break;
571                                 }
572                         }
573                 }
574
575                 if (content && caption && label)
576                         break;
577         }
578
579         return std::make_tuple(type, content, caption, label);
580 }
581
582
583 void docbookSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
584                                            const InsetLabel * label, std::vector<const InsetCollapsible *> const & subfigures)
585 {
586         // Ensure there is no label output, it is supposed to be handled as xml:id.
587         OutputParams rpNoLabel = runparams;
588         if (label)
589                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
590
591         // First, open the formal group.
592         docstring attr = docstring();
593         if (label)
594                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
595
596         xs.startDivision(false);
597         xs << xml::StartTag("formalgroup", attr);
598         xs << xml::CR();
599
600         xs << xml::StartTag("title"); // Don't take attr here, the ID should only go in one place, not two.
601         if (caption) {
602                 caption->getCaptionAsDocBook(xs, rpNoLabel);
603         } else {
604                 xs << "No caption";
605                 // No caption has been detected, but this tag is required for the document to be valid DocBook.
606         }
607         xs << xml::EndTag("title");
608         xs << xml::CR();
609
610         // Deal with each subfigure individually. This should also deal with their caption and their label.
611         // This should be a recursive call to InsetFloat.
612         // An item in subfigure should either be an InsetBox containing an InsetFloat, or an InsetBox directly containing
613         // an image or a table, or directly an InsetFloat.
614         for (const InsetCollapsible * subfigure: subfigures) {
615                 if (subfigure == nullptr)
616                         continue;
617
618                 // The collapsible may already be a float (InsetFloat).
619                 if (dynamic_cast<const InsetFloat *>(subfigure)) {
620                         subfigure->docbook(xs, runparams);
621                         continue;
622                 }
623
624                 // Subfigures are in boxes, then in InsetFloat.
625                 {
626                         bool foundInsetFloat = false;
627                         for (const auto &it : subfigure->paragraphs()) {
628                                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
629                                         const Inset *inset = it.getInset(posIn);
630                                         if (inset && inset->lyxCode() == FLOAT_CODE) {
631                                                 foundInsetFloat = true;
632                                                 inset->docbook(xs, runparams);
633                                                 break;
634                                         }
635                                 }
636
637                                 if (foundInsetFloat)
638                                         break;
639                         }
640                         if (foundInsetFloat)
641                                 continue;
642                 }
643
644                 // Subfigures are in boxes, then directly an image or a table. In that case, generate the whole content of the
645                 // InsetBox, but not the box container.
646                 // Impose some model on the subfigure: at most a caption, at most a label, exactly one figure or one table.
647                 {
648                         InsetCode stype = NO_CODE;
649                         const Inset * scontent = nullptr;
650                         const InsetCaption * scaption = nullptr;
651                         const InsetLabel * slabel = nullptr;
652
653                         std::tie(stype, scontent, scaption, slabel) = docbookParseHopelessSubfigure(subfigure);
654
655                         // If there is something, generate it. This is very much like docbookNoSubfigures, but many things
656                         // must be coded differently because there is no float.
657                         // TODO: some code is identical to Floating, like Floating::docbookTag or Floating::docbookCaption. How to reuse that code?
658                         if (scontent) {
659                                 // Floating::docbookCaption()
660                                 string docbook_caption = "caption"; // This is already correct for tables.
661                                 if (stype == GRAPHICS_CODE)
662                                         docbook_caption = "title";
663
664                                 // Floating::docbookTag() with hasTitle = true, as we are in formalgroup.
665                                 string stag = "float";
666                                 if (stype == GRAPHICS_CODE)
667                                         stag = "figure";
668                                 else if (stype == TABULAR_CODE)
669                                         stag = "table";
670
671                                 // Ensure there is no label output, it is supposed to be handled as xml:id.
672                                 if (slabel)
673                                         rpNoLabel.docbook_anchors_to_ignore.emplace(slabel->screenLabel());
674
675                                 // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
676                                 // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
677                                 OutputParams rpNoTitle = runparams;
678                                 rpNoTitle.docbook_in_float = true;
679                                 if (stype == TABULAR_CODE)
680                                         rpNoTitle.docbook_in_table = true;
681
682                                 // Organisation: <float> <title if any/> <contents without title/> </float>.
683                                 docstring sattr = docstring();
684                                 if (slabel)
685                                         sattr += "xml:id=\"" + xml::cleanID(slabel->screenLabel()) + "\"";
686                                 // No layout way of adding attributes, unlike the normal code path.
687
688                                 xs << xml::StartTag(stag, sattr);
689                                 xs << xml::CR();
690                                 xs << xml::StartTag(docbook_caption);
691                                 if (scaption)
692                                         scaption->getCaptionAsDocBook(xs, rpNoLabel);
693                                 else // Mandatory in formalgroup.
694                                         xs << "No caption detected";
695                                 xs << xml::EndTag(docbook_caption);
696                                 xs << xml::CR();
697                                 scontent->docbook(xs, rpNoTitle);
698                                 xs << xml::EndTag(stag);
699                                 xs << xml::CR();
700
701                                 // This subfigure could be generated.
702                                 continue;
703                         }
704                 }
705
706                 // If there is no InsetFloat in the inset, output a warning.
707                 xs << XMLStream::ESCAPE_NONE << "Error: no float found in the box. "
708                                                         "To use subfigures in DocBook, elements must be wrapped in a float "
709                                     "inset and have a title/caption.";
710                 // TODO: could also output a table, that would ensure that the document is correct and *displays* correctly (but without the right semantics), instead of just an error.
711
712                 // Recurse to generate as much content as possible (avoid any loss).
713                 subfigure->docbook(xs, runparams);
714         }
715
716         // Every subfigure is done: close the formal group.
717         xs << xml::EndTag("formalgroup");
718         xs << xml::CR();
719         xs.endDivision();
720 }
721
722
723 void docbookGenerateFillerMedia(XMLStream & xs)
724 {
725         xs << xml::StartTag("mediaobject");
726         xs << xml::CR();
727         xs << xml::StartTag("textobject");
728         xs << xml::CR();
729         xs << xml::StartTag("phrase");
730         xs << "This figure is empty.";
731         xs << xml::EndTag("phrase");
732         xs << xml::CR();
733         xs << xml::EndTag("textobject");
734         xs << xml::CR();
735         xs << xml::EndTag("mediaobject");
736         xs << xml::CR();
737 }
738
739
740 void docbookGenerateFillerTable(XMLStream & xs, BufferParams::TableOutput format)
741 {
742         switch (format) {
743         case BufferParams::HTMLTable:
744                 xs << xml::StartTag("tr");
745                 xs << xml::CR();
746                 xs << xml::StartTag("td");
747                 xs << "This table is empty.";
748                 xs << xml::EndTag("td");
749                 xs << xml::CR();
750                 xs << xml::EndTag("tr");
751                 xs << xml::CR();
752                 break;
753         case BufferParams::CALSTable:
754                 // CALS tables allow for <mediaobject>, use that instead.
755                 docbookGenerateFillerMedia(xs);
756                 break;
757         }
758 }
759
760
761 void docbookNoSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
762                          const InsetLabel * label, Floating const & ftype, const InsetFloat * thisFloat) {
763         // Ensure there is no label output, it is supposed to be handled as xml:id.
764         OutputParams rpNoLabel = runparams;
765         if (label)
766                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
767
768         // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
769         // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
770         OutputParams rpNoTitle = runparams;
771         rpNoTitle.docbook_in_float = true;
772         if (ftype.docbookFloatType() == "table")
773                 rpNoTitle.docbook_in_table = true;
774
775         // Generate the contents of the float (to check for emptiness).
776         odocstringstream osFloatContent;
777         bool hasFloat = false;
778
779         if (thisFloat) {
780                 XMLStream xsFloatContent(osFloatContent);
781                 thisFloat->InsetText::docbook(xsFloatContent, rpNoTitle);
782                 hasFloat = !osFloatContent.str().empty();
783         }
784
785         // Do the same for the caption.
786         odocstringstream osCaptionContent;
787         bool hasCaption = false;
788
789         if (caption != nullptr) {
790                 XMLStream xsCaptionContent(osCaptionContent);
791                 caption->getCaptionAsDocBook(xsCaptionContent, rpNoLabel);
792                 hasCaption = !osCaptionContent.str().empty();
793         }
794
795         // Organisation: <float with xml:id if any> <title if any/> <contents without title nor xml:id/> </float>.
796         // Titles and xml:id are generated with specific insets and must be dealt with using OutputParams.
797
798         // - Generate the attributes for the float tag.
799         docstring attr = docstring();
800         if (label)
801                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
802         if (!ftype.docbookAttr().empty()) {
803                 if (!attr.empty())
804                         attr += " ";
805                 attr += from_utf8(ftype.docbookAttr());
806         }
807
808         // - Open the float tag.
809         xs << xml::StartTag(ftype.docbookTag(hasCaption), attr);
810         xs << xml::CR();
811
812         // - Generate the caption.
813         if (hasCaption) {
814                 string const &titleTag = ftype.docbookCaption();
815                 xs << xml::StartTag(titleTag);
816                 xs << XMLStream::ESCAPE_NONE << osCaptionContent.str();
817                 xs << xml::EndTag(titleTag);
818                 xs << xml::CR();
819         }
820
821         // - Output the actual content of the float or some dummy content (to ensure that the output
822         // document is valid). Use HTML tables by default, unless an InsetFloat is given.
823         if (hasFloat)
824                 xs << XMLStream::ESCAPE_NONE << osFloatContent.str();
825         else if (ftype.docbookFloatType() == "table") {
826                 BufferParams::TableOutput tableFormat = BufferParams::HTMLTable;
827                 if (thisFloat)
828                         tableFormat = thisFloat->buffer().params().docbook_table_output;
829                 docbookGenerateFillerTable(xs, tableFormat);
830         } else
831                 docbookGenerateFillerMedia(xs);
832
833         // - Close the float.
834         xs << xml::EndTag(ftype.docbookTag(hasCaption));
835         xs << xml::CR();
836 }
837
838
839 void InsetFloat::docbook(XMLStream & xs, OutputParams const & runparams) const
840 {
841         const InsetCaption* caption = getCaptionInset();
842         const InsetLabel* label = getLabelInset();
843
844         // Determine whether the float has subfigures.
845         std::vector<const InsetCollapsible *> subfigures;
846         auto end = paragraphs().end();
847         for (auto it = paragraphs().begin(); it != end; ++it) {
848                 std::vector<const InsetCollapsible *> foundSubfigures = findSubfiguresInParagraph(*it);
849                 if (!foundSubfigures.empty()) {
850                         subfigures.reserve(subfigures.size() + foundSubfigures.size());
851                         subfigures.insert(subfigures.end(), foundSubfigures.begin(), foundSubfigures.end());
852                 }
853         }
854
855         // Gather a few things from global environment that are shared between all following cases.
856         FloatList const & floats = buffer().params().documentClass().floats();
857         Floating const & ftype = floats.getType(params_.type);
858
859         // Switch on subfigures.
860         if (!subfigures.empty())
861                 docbookSubfigures(xs, runparams, caption, label, subfigures);
862         else
863                 docbookNoSubfigures(xs, runparams, caption, label, ftype, this);
864 }
865
866
867 bool InsetFloat::insetAllowed(InsetCode code) const
868 {
869         // The case that code == FLOAT_CODE is handled in Text.cpp,
870         // because we need to know what type of float is meant.
871         switch(code) {
872         case WRAP_CODE:
873         case FOOT_CODE:
874         case MARGIN_CODE:
875                 return false;
876         default:
877                 return InsetCaptionable::insetAllowed(code);
878         }
879 }
880
881
882 void InsetFloat::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
883 {
884         InsetCaptionable::updateBuffer(it, utype, deleted);
885         bool const subflt = (it.innerInsetOfType(FLOAT_CODE)
886                              || it.innerInsetOfType(WRAP_CODE));
887         setSubfloat(subflt);
888 }
889
890
891 void InsetFloat::setWide(bool w, bool update_label)
892 {
893         if (!buffer().params().documentClass().floats().allowsWide(params_.type))
894                 params_.wide = false;
895         else
896                 params_.wide = w;
897         if (update_label)
898                 setNewLabel();
899 }
900
901
902 void InsetFloat::setSideways(bool s, bool update_label)
903 {
904         if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
905                 params_.sideways = false;
906         else
907                 params_.sideways = s;
908         if (update_label)
909                 setNewLabel();
910 }
911
912
913 void InsetFloat::setSubfloat(bool s, bool update_label)
914 {
915         params_.subfloat = s;
916         if (update_label)
917                 setNewLabel();
918 }
919
920
921 void InsetFloat::setNewLabel()
922 {
923         docstring lab = _("Float: ");
924
925         if (params_.subfloat)
926                 lab = _("Subfloat: ");
927
928         lab += floatName(params_.type);
929
930         FloatList const & floats = buffer().params().documentClass().floats();
931
932         if (params_.wide && floats.allowsWide(params_.type))
933                 lab += '*';
934
935         if (params_.sideways && floats.allowsSideways(params_.type))
936                 lab += _(" (sideways)");
937
938         setLabel(lab);
939 }
940
941
942 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
943 {
944         return !params_.subfloat && newtype != "Unnumbered";
945 }
946
947
948 TexString InsetFloat::getCaption(OutputParams const & runparams) const
949 {
950         InsetCaption const * ins = getCaptionInset();
951         if (ins == 0)
952                 return TexString();
953
954         otexstringstream os;
955         ins->getArgs(os, runparams);
956
957         if (!runparams.nice)
958                 // increase TexRow precision in non-nice mode
959                 os << safebreakln;
960         os << '[';
961         otexstringstream os2;
962         ins->getArgument(os2, runparams);
963         TexString ts = os2.release();
964         docstring & arg = ts.str;
965         // Protect ']'
966         if (arg.find(']') != docstring::npos)
967                 arg = '{' + arg + '}';
968         os << std::move(ts);
969         os << ']';
970         if (!runparams.nice)
971                 os << safebreakln;
972         return os.release();
973 }
974
975
976 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
977 {
978         params = InsetFloatParams();
979         if (in.empty())
980                 return;
981
982         istringstream data(in);
983         Lexer lex;
984         lex.setStream(data);
985         lex.setContext("InsetFloat::string2params");
986         params.read(lex);
987 }
988
989
990 string InsetFloat::params2string(InsetFloatParams const & params)
991 {
992         ostringstream data;
993         params.write(data);
994         return data.str();
995 }
996
997
998 } // namespace lyx