]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
DocBook: for empty figures, output a message.
[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 "Lexer.h"
34 #include "xml.h"
35 #include "output_docbook.h"
36 #include "output_xhtml.h"
37 #include "ParIterator.h"
38 #include "TexRow.h"
39 #include "texstream.h"
40 #include "TextClass.h"
41 #include "InsetList.h"
42
43 #include "support/debug.h"
44 #include "support/docstream.h"
45 #include "support/gettext.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 LyXAlignment InsetFloat::contentAlignment() const
260 {
261         LyXAlignment align = LYX_ALIGN_NONE;
262         string alignment = getAlignment();
263         if (alignment == "left")
264                 align = LYX_ALIGN_LEFT;
265         else if (alignment == "center")
266                 align = LYX_ALIGN_CENTER;
267         else if (alignment == "right")
268                 align = LYX_ALIGN_RIGHT;
269
270         return align;
271 }
272
273
274 void InsetFloatParams::write(ostream & os) const
275 {
276         if (type.empty()) {
277                 // Better this than creating a parse error. This in fact happens in the
278                 // parameters dialog via InsetFloatParams::params2string.
279                 os << "senseless" << '\n';
280         } else
281                 os << type << '\n';
282
283         if (!placement.empty())
284                 os << "placement " << placement << "\n";
285         if (!alignment.empty())
286                 os << "alignment " << alignment << "\n";
287
288         if (wide)
289                 os << "wide true\n";
290         else
291                 os << "wide false\n";
292
293         if (sideways)
294                 os << "sideways true\n";
295         else
296                 os << "sideways false\n";
297 }
298
299
300 void InsetFloatParams::read(Lexer & lex)
301 {
302         lex.setContext("InsetFloatParams::read");
303         lex >> type;
304         if (lex.checkFor("placement"))
305                 lex >> placement;
306         if (lex.checkFor("alignment"))
307                 lex >> alignment;
308         lex >> "wide" >> wide;
309         lex >> "sideways" >> sideways;
310 }
311
312
313 void InsetFloat::write(ostream & os) const
314 {
315         os << "Float ";
316         params_.write(os);
317         InsetCaptionable::write(os);
318 }
319
320
321 void InsetFloat::read(Lexer & lex)
322 {
323         params_.read(lex);
324         InsetCaptionable::read(lex);
325         setCaptionType(params_.type);
326 }
327
328
329 void InsetFloat::validate(LaTeXFeatures & features) const
330 {
331         if (support::contains(params_.placement, 'H'))
332                 features.require("float");
333
334         if (params_.sideways)
335                 features.require("rotfloat");
336
337         if (features.inFloat())
338                 features.require("subfig");
339
340         if (features.inDeletedInset()) {
341                 features.require("tikz");
342                 features.require("ct-tikz-object-sout");
343         }
344
345         features.useFloat(params_.type, features.inFloat());
346         features.inFloat(true);
347         InsetCaptionable::validate(features);
348         features.inFloat(false);
349 }
350
351
352 docstring InsetFloat::xhtml(XMLStream & xs, OutputParams const & rp) const
353 {
354         FloatList const & floats = buffer().params().documentClass().floats();
355         Floating const & ftype = floats.getType(params_.type);
356         string const & htmltype = ftype.htmlTag();
357         string const & attr = ftype.htmlAttrib();
358
359         odocstringstream ods;
360         XMLStream newxs(ods);
361         newxs << xml::StartTag(htmltype, attr);
362         InsetText::XHTMLOptions const opts =
363                 InsetText::WriteLabel | InsetText::WriteInnerTag;
364         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
365         newxs << xml::EndTag(htmltype);
366
367         if (rp.inFloat == OutputParams::NONFLOAT) {
368                 // In this case, this float needs to be deferred, but we'll put it
369                 // before anything the text itself deferred.
370                 deferred = ods.str() + '\n' + deferred;
371         } else {
372                 // In this case, the whole thing is already being deferred, so
373                 // we can write to the stream.
374                 // Note that things will already have been escaped, so we do not
375                 // want to escape them again.
376                 xs << XMLStream::ESCAPE_NONE << ods.str();
377         }
378         return deferred;
379 }
380
381
382 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
383 {
384         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
385                 if (!paragraphs().empty() && !runparams_in.nice)
386                         // improve TexRow precision in non-nice mode
387                         os << safebreakln;
388
389                 if (runparams_in.moving_arg)
390                         os << "\\protect";
391                 os << "\\subfloat";
392
393                 OutputParams rp = runparams_in;
394                 rp.moving_arg = true;
395                 rp.inFloat = OutputParams::SUBFLOAT;
396                 os << getCaption(rp);
397                 os << '{';
398                 // The main argument is the contents of the float. This is not a moving argument.
399                 rp.moving_arg = false;
400                 InsetText::latex(os, rp);
401                 os << "}";
402
403                 return;
404         }
405         OutputParams runparams(runparams_in);
406         runparams.inFloat = OutputParams::MAINFLOAT;
407
408         FloatList const & floats = buffer().params().documentClass().floats();
409         string tmptype = params_.type;
410         if (params_.sideways && floats.allowsSideways(params_.type))
411                 tmptype = "sideways" + params_.type;
412         if (params_.wide && floats.allowsWide(params_.type)
413                 && (!params_.sideways ||
414                      params_.type == "figure" ||
415                      params_.type == "table"))
416                 tmptype += "*";
417         // Figure out the float placement to use.
418         // From lowest to highest:
419         // - float default placement
420         // - document wide default placement
421         // - specific float placement
422         string tmpplacement;
423         string const buf_placement = buffer().params().float_placement;
424         string const def_placement = floats.defaultPlacement(params_.type);
425         if (params_.placement == "document"
426             && !buf_placement.empty()
427             && buf_placement != def_placement) {
428                 tmpplacement = buf_placement;
429         } else if (!params_.placement.empty()
430                    && params_.placement != "document"
431                    && params_.placement != def_placement) {
432                 tmpplacement = params_.placement;
433         }
434
435         // Check if placement is allowed by this float
436         string const allowed_placement =
437                 floats.allowedPlacement(params_.type);
438         string placement;
439         string::const_iterator lit = tmpplacement.begin();
440         string::const_iterator end = tmpplacement.end();
441         for (; lit != end; ++lit) {
442                 if (contains(allowed_placement, *lit))
443                         placement += *lit;
444         }
445
446         // Force \begin{<floatname>} to appear in a new line.
447         os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
448         if (runparams.lastid != -1)
449                 os.texrow().start(runparams.lastid, runparams.lastpos);
450         // We only output placement if different from the def_placement.
451         // sidewaysfloats always use their own page,
452         // therefore don't output the p option that is always set
453         if (!placement.empty()
454             && (!params_.sideways || from_ascii(placement) != "p"))
455                 os << '[' << from_ascii(placement) << ']';
456         os << '\n';
457
458         if (runparams.inDeletedInset) {
459                 // This has to be done manually since we need it inside the float
460                 OutputParams::CtObject ctobject = runparams.ctObject;
461                 runparams.ctObject = OutputParams::CT_DISPLAYOBJECT;
462                 Changes::latexMarkChange(os, buffer().params(), Change(Change::UNCHANGED),
463                                          Change(Change::DELETED), runparams);
464                 runparams.ctObject = ctobject;
465         }
466
467         string alignment = getAlignment();
468         if (alignment == "left")
469                 os << "\\raggedright" << breakln;
470         else if (alignment == "center")
471                 os << "\\centering" << breakln;
472         else if (alignment == "right")
473                 os << "\\raggedleft" << breakln;
474
475         InsetText::latex(os, runparams);
476
477         if (runparams.inDeletedInset)
478                 os << "}";
479
480         // Force \end{<floatname>} to appear in a new line.
481         os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
482 }
483
484
485 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
486 {
487         os << '[' << buffer().B_("float") << ' '
488                 << floatName(params_.type) << ":\n";
489         InsetText::plaintext(os, runparams, max_length);
490         os << "\n]";
491
492         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
493 }
494
495
496 std::vector<const InsetCollapsible *> findSubfiguresInParagraph(const Paragraph &par)
497 {
498
499         // Don't make the hypothesis that all subfigures are in the same paragraph.
500         // Similarly, there may be several subfigures in the same paragraph (most likely case, based on the documentation).
501         // Any box is considered as a subfigure, even though the most likely case is \minipage.
502         // Boxes are not required to make subfigures. The common root between InsetBox and InsetFLoat is InsetCollapsible.
503         std::vector<const InsetCollapsible *> subfigures;
504         for (pos_type pos = 0; pos < par.size(); ++pos) {
505                 const Inset *inset = par.getInset(pos);
506                 if (!inset)
507                         continue;
508                 if (const auto box = dynamic_cast<const InsetBox *>(inset))
509                         subfigures.push_back(box);
510                 else if (const auto fl = dynamic_cast<const InsetFloat *>(inset))
511                         subfigures.push_back(fl);
512         }
513         return subfigures;
514 }
515
516
517 /// Takes an unstructured subfigure container (typically, an InsetBox) and find the elements within:
518 /// actual content (image or table), maybe a caption, maybe a label.
519 std::tuple<InsetCode, const Inset *, const InsetCaption *, const InsetLabel *> docbookParseHopelessSubfigure(const InsetText * subfigure)
520 {
521         InsetCode type = NO_CODE;
522         const Inset * content = nullptr;
523         const InsetCaption * caption = nullptr;
524         const InsetLabel * label = nullptr;
525
526         for (const auto & it : subfigure->paragraphs()) {
527                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
528                         const Inset * inset = it.getInset(posIn);
529                         if (inset) {
530                                 switch (inset->lyxCode()) {
531                                         case GRAPHICS_CODE:
532                                         case TABULAR_CODE:
533                                                 if (!content) {
534                                                         content = inset;
535                                                         type = inset->lyxCode();
536                                                 }
537                                                 break;
538                                         case CAPTION_CODE:
539                                                 if (!caption) {
540                                                         caption = dynamic_cast<const InsetCaption *>(inset);
541
542                                                         // A label often hides in a caption. Make a simplified version of the main loop.
543                                                         if (!label) {
544                                                                 for (const auto &cit : caption->paragraphs()) {
545                                                                         for (pos_type cposIn = 0; cposIn < cit.size(); ++cposIn) {
546                                                                                 const Inset *cinset = cit.getInset(posIn);
547                                                                                 if (cinset && cinset->lyxCode() == LABEL_CODE) {
548                                                                                         label = dynamic_cast<const InsetLabel *>(cinset);
549                                                                                         break;
550                                                                                 }
551                                                                         }
552
553                                                                         if (label)
554                                                                                 break;
555                                                                 }
556                                                         }
557                                                 }
558                                                 break;
559                                         case LABEL_CODE:
560                                                 if (!label)
561                                                         label = dynamic_cast<const InsetLabel *>(inset);
562                                                 break;
563                                         default:
564                                                 break;
565                                 }
566                         }
567                 }
568
569                 if (content && caption && label)
570                         break;
571         }
572
573         return std::make_tuple(type, content, caption, label);
574 }
575
576
577 void docbookSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
578                                            const InsetLabel * label, std::vector<const InsetCollapsible *> const & subfigures)
579 {
580         // Ensure there is no label output, it is supposed to be handled as xml:id.
581         OutputParams rpNoLabel = runparams;
582         if (label)
583                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
584
585         // First, open the formal group.
586         docstring attr = docstring();
587         if (label)
588                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
589
590         xs.startDivision(false);
591         xs << xml::StartTag("formalgroup", attr);
592         xs << xml::CR();
593
594         xs << xml::StartTag("title"); // Don't take attr here, the ID should only go in one place, not two.
595         if (caption) {
596                 caption->getCaptionAsDocBook(xs, rpNoLabel);
597         } else {
598                 xs << "No caption";
599                 // No caption has been detected, but this tag is required for the document to be valid DocBook.
600         }
601         xs << xml::EndTag("title");
602         xs << xml::CR();
603
604         // Deal with each subfigure individually. This should also deal with their caption and their label.
605         // This should be a recursive call to InsetFloat.
606         // An item in subfigure should either be an InsetBox containing an InsetFloat, or an InsetBox directly containing
607         // an image or a table, or directly an InsetFloat.
608         for (const InsetCollapsible * subfigure: subfigures) {
609                 if (subfigure == nullptr)
610                         continue;
611
612                 // The collapsible may already be a float (InsetFloat).
613                 if (dynamic_cast<const InsetFloat *>(subfigure)) {
614                         subfigure->docbook(xs, runparams);
615                         continue;
616                 }
617
618                 // Subfigures are in boxes, then in InsetFloat.
619                 {
620                         bool foundInsetFloat = false;
621                         for (const auto &it : subfigure->paragraphs()) {
622                                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
623                                         const Inset *inset = it.getInset(posIn);
624                                         if (inset && inset->lyxCode() == FLOAT_CODE) {
625                                                 foundInsetFloat = true;
626                                                 inset->docbook(xs, runparams);
627                                                 break;
628                                         }
629                                 }
630
631                                 if (foundInsetFloat)
632                                         break;
633                         }
634                         if (foundInsetFloat)
635                                 continue;
636                 }
637
638                 // Subfigures are in boxes, then directly an image or a table. In that case, generate the whole content of the
639                 // InsetBox, but not the box container.
640                 // Impose some model on the subfigure: at most a caption, at most a label, exactly one figure or one table.
641                 {
642                         InsetCode stype = NO_CODE;
643                         const Inset * scontent = nullptr;
644                         const InsetCaption * scaption = nullptr;
645                         const InsetLabel * slabel = nullptr;
646
647                         std::tie(stype, scontent, scaption, slabel) = docbookParseHopelessSubfigure(subfigure);
648
649                         // If there is something, generate it. This is very much like docbookNoSubfigures, but many things
650                         // must be coded differently because there is no float.
651                         // TODO: some code is identical to Floating, like Floating::docbookTag or Floating::docbookCaption. How to reuse that code?
652                         if (scontent) {
653                                 // Floating::docbookCaption()
654                                 string docbook_caption = "caption"; // This is already correct for tables.
655                                 if (stype == GRAPHICS_CODE)
656                                         docbook_caption = "title";
657
658                                 // Floating::docbookTag() with hasTitle = true, as we are in formalgroup.
659                                 string stag = "float";
660                                 if (stype == GRAPHICS_CODE)
661                                         stag = "figure";
662                                 else if (stype == TABULAR_CODE)
663                                         stag = "table";
664
665                                 // Ensure there is no label output, it is supposed to be handled as xml:id.
666                                 if (slabel)
667                                         rpNoLabel.docbook_anchors_to_ignore.emplace(slabel->screenLabel());
668
669                                 // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
670                                 // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
671                                 OutputParams rpNoTitle = runparams;
672                                 rpNoTitle.docbook_in_float = true;
673                                 if (stype == TABULAR_CODE)
674                                         rpNoTitle.docbook_in_table = true;
675
676                                 // Organisation: <float> <title if any/> <contents without title/> </float>.
677                                 docstring sattr = docstring();
678                                 if (slabel)
679                                         sattr += "xml:id=\"" + xml::cleanID(slabel->screenLabel()) + "\"";
680                                 // No layout way of adding attributes, unlike the normal code path.
681
682                                 xs << xml::StartTag(stag, sattr);
683                                 xs << xml::CR();
684                                 xs << xml::StartTag(docbook_caption);
685                                 if (scaption)
686                                         scaption->getCaptionAsDocBook(xs, rpNoLabel);
687                                 else // Mandatory in formalgroup.
688                                         xs << "No caption detected";
689                                 xs << xml::EndTag(docbook_caption);
690                                 xs << xml::CR();
691                                 scontent->docbook(xs, rpNoTitle);
692                                 xs << xml::EndTag(stag);
693                                 xs << xml::CR();
694
695                                 // This subfigure could be generated.
696                                 continue;
697                         }
698                 }
699
700                 // If there is no InsetFloat in the inset, output a warning.
701                 xs << XMLStream::ESCAPE_NONE << "Error: no float found in the box. "
702                                                         "To use subfigures in DocBook, elements must be wrapped in a float "
703                                     "inset and have a title/caption.";
704                 // 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.
705
706                 // Recurse to generate as much content as possible (avoid any loss).
707                 subfigure->docbook(xs, runparams);
708         }
709
710         // Every subfigure is done: close the formal group.
711         xs << xml::EndTag("formalgroup");
712         xs << xml::CR();
713         xs.endDivision();
714 }
715
716
717 void docbookNoSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
718                          const InsetLabel * label, Floating const & ftype, const InsetFloat * thisFloat)
719 {
720         string const &titleTag = ftype.docbookCaption();
721
722         // Ensure there is no label output, it is supposed to be handled as xml:id.
723         OutputParams rpNoLabel = runparams;
724         if (label)
725                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
726
727         // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
728         // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
729         OutputParams rpNoTitle = runparams;
730         rpNoTitle.docbook_in_float = true;
731         if (ftype.docbookFloatType() == "table")
732                 rpNoTitle.docbook_in_table = true;
733
734         // Generate the contents of the float (to check for emptiness).
735         odocstringstream os2;
736         XMLStream xs2(os2);
737         thisFloat->InsetText::docbook(xs, rpNoTitle);
738
739         // Organisation: <float> <title if any/> <contents without title/> </float>.
740         docstring attr = docstring();
741         if (label)
742                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
743         if (!ftype.docbookAttr().empty()) {
744                 if (!attr.empty())
745                         attr += " ";
746                 attr += from_utf8(ftype.docbookAttr());
747         }
748
749         xs << xml::StartTag(ftype.docbookTag(caption != nullptr), attr);
750         xs << xml::CR();
751         if (caption) {
752                 xs << xml::StartTag(titleTag);
753                 caption->getCaptionAsDocBook(xs, rpNoLabel);
754                 xs << xml::EndTag(titleTag);
755                 xs << xml::CR();
756         }
757
758         if (!os2.str().empty()) {
759                 xs << XMLStream::ESCAPE_NONE << os2.str();
760         } else {
761                 xs << xml::StartTag("mediaobject");
762                 xs << xml::CR();
763                 xs << xml::StartTag("textobject");
764                 xs << xml::CR();
765                 xs << xml::StartTag("phrase");
766                 xs << "This figure is empty.";
767                 xs << xml::EndTag("phrase");
768                 xs << xml::CR();
769                 xs << xml::EndTag("textobject");
770                 xs << xml::CR();
771                 xs << xml::EndTag("mediaobject");
772                 xs << xml::CR();
773         }
774
775         xs << xml::EndTag(ftype.docbookTag(caption != nullptr));
776         xs << xml::CR();
777 }
778
779
780 void InsetFloat::docbook(XMLStream & xs, OutputParams const & runparams) const
781 {
782 //      if (runparams.docbook_in_par) {
783 //              xs << xml::EndTag("para");
784 //              xs << xml::CR();
785 //      }
786
787         const InsetCaption* caption = getCaptionInset();
788         const InsetLabel* label = getLabelInset();
789
790         // Determine whether the float has subfigures.
791         std::vector<const InsetCollapsible *> subfigures;
792         auto end = paragraphs().end();
793         for (auto it = paragraphs().begin(); it != end; ++it) {
794                 std::vector<const InsetCollapsible *> foundSubfigures = findSubfiguresInParagraph(*it);
795                 if (!foundSubfigures.empty()) {
796                         subfigures.reserve(subfigures.size() + foundSubfigures.size());
797                         subfigures.insert(subfigures.end(), foundSubfigures.begin(), foundSubfigures.end());
798                 }
799         }
800
801         // Gather a few things from global environment that are shared between all following cases.
802         FloatList const & floats = buffer().params().documentClass().floats();
803         Floating const & ftype = floats.getType(params_.type);
804
805         // Switch on subfigures.
806         if (!subfigures.empty())
807                 docbookSubfigures(xs, runparams, caption, label, subfigures);
808         else
809                 docbookNoSubfigures(xs, runparams, caption, label, ftype, this);
810
811 //      if (runparams.docbook_in_par) {
812 //              xs << xml::CR();
813 //              xs << xml::StartTag("para");
814 //      }
815 }
816
817
818 bool InsetFloat::insetAllowed(InsetCode code) const
819 {
820         // The case that code == FLOAT_CODE is handled in Text3.cpp,
821         // because we need to know what type of float is meant.
822         switch(code) {
823         case WRAP_CODE:
824         case FOOT_CODE:
825         case MARGIN_CODE:
826                 return false;
827         default:
828                 return InsetCaptionable::insetAllowed(code);
829         }
830 }
831
832
833 void InsetFloat::setWide(bool w, bool update_label)
834 {
835         if (!buffer().params().documentClass().floats().allowsWide(params_.type))
836                 params_.wide = false;
837         else
838             params_.wide = w;
839         if (update_label)
840                 setNewLabel();
841 }
842
843
844 void InsetFloat::setSideways(bool s, bool update_label)
845 {
846         if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
847                 params_.sideways = false;
848         else
849                 params_.sideways = s;
850         if (update_label)
851                 setNewLabel();
852 }
853
854
855 void InsetFloat::setSubfloat(bool s, bool update_label)
856 {
857         params_.subfloat = s;
858         if (update_label)
859                 setNewLabel();
860 }
861
862
863 void InsetFloat::setNewLabel()
864 {
865         docstring lab = _("float: ");
866
867         if (params_.subfloat)
868                 lab = _("subfloat: ");
869
870         lab += floatName(params_.type);
871
872         FloatList const & floats = buffer().params().documentClass().floats();
873
874         if (params_.wide && floats.allowsWide(params_.type))
875                 lab += '*';
876
877         if (params_.sideways && floats.allowsSideways(params_.type))
878                 lab += _(" (sideways)");
879
880         setLabel(lab);
881 }
882
883
884 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
885 {
886         return !params_.subfloat && newtype != "Unnumbered";
887 }
888
889
890 TexString InsetFloat::getCaption(OutputParams const & runparams) const
891 {
892         InsetCaption const * ins = getCaptionInset();
893         if (ins == 0)
894                 return TexString();
895
896         otexstringstream os;
897         ins->getArgs(os, runparams);
898
899         if (!runparams.nice)
900                 // increase TexRow precision in non-nice mode
901                 os << safebreakln;
902         os << '[';
903         otexstringstream os2;
904         ins->getArgument(os2, runparams);
905         TexString ts = os2.release();
906         docstring & arg = ts.str;
907         // Protect ']'
908         if (arg.find(']') != docstring::npos)
909                 arg = '{' + arg + '}';
910         os << move(ts);
911         os << ']';
912         if (!runparams.nice)
913                 os << safebreakln;
914         return os.release();
915 }
916
917
918 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
919 {
920         params = InsetFloatParams();
921         if (in.empty())
922                 return;
923
924         istringstream data(in);
925         Lexer lex;
926         lex.setStream(data);
927         lex.setContext("InsetFloat::string2params");
928         params.read(lex);
929 }
930
931
932 string InsetFloat::params2string(InsetFloatParams const & params)
933 {
934         ostringstream data;
935         params.write(data);
936         return data.str();
937 }
938
939
940 } // namespace lyx