]> git.lyx.org Git - features.git/blob - src/insets/InsetFloat.cpp
Move include of own header to the top. Fix dependencies
[features.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 const InsetLabel* findLabelInParagraph(const Paragraph &par)
518 {
519         for (pos_type pos = 0; pos < par.size(); ++pos) {
520                 // If this inset is a subfigure, skip it.
521                 const Inset *inset = par.getInset(pos);
522                 if (dynamic_cast<const InsetBox *>(inset)) {
523                         continue;
524                 }
525
526                 // Maybe an inset is directly a label, in which case no more work is needed.
527                 if (inset && dynamic_cast<const InsetLabel *>(inset))
528                         return dynamic_cast<const InsetLabel *>(inset);
529
530                 // More likely, the label is hidden in an inset of a paragraph (only if a subtype of InsetText).
531                 if (!dynamic_cast<const InsetText *>(inset))
532                         continue;
533
534                 auto insetAsText = dynamic_cast<const InsetText *>(inset);
535                 auto itIn = insetAsText->paragraphs().begin();
536                 auto endIn = insetAsText->paragraphs().end();
537                 for (; itIn != endIn; ++itIn) {
538                         for (pos_type posIn = 0; posIn < itIn->size(); ++posIn) {
539                                 const Inset *insetIn = itIn->getInset(posIn);
540                                 if (insetIn && dynamic_cast<const InsetLabel *>(insetIn)) {
541                                         return dynamic_cast<const InsetLabel *>(insetIn);
542                                 }
543                         }
544                 }
545
546                 // Obviously, this solution does not scale with more levels of paragraphs-insets, but this should be enough.
547         }
548
549         return nullptr;
550 }
551
552
553 const InsetCaption* findCaptionInParagraph(const Paragraph &par)
554 {
555         // Don't dive too deep, otherwise, this could be a subfigure caption.
556         for (pos_type pos = 0; pos < par.size(); ++pos) {
557                 // If this inset is a subfigure, skip it.
558                 const Inset *inset = par.getInset(pos);
559                 if (dynamic_cast<const InsetBox *>(inset))
560                         continue;
561
562                 if (inset && dynamic_cast<const InsetCaption *>(inset))
563                         return dynamic_cast<const InsetCaption *>(inset);
564         }
565
566         return nullptr;
567 }
568
569
570 /// Takes an unstructured subfigure container (typically, an InsetBox) and find the elements within:
571 /// actual content (image or table), maybe a caption, maybe a label.
572 std::tuple<InsetCode, const Inset *, const InsetCaption *, const InsetLabel *> docbookParseHopelessSubfigure(const InsetText * subfigure)
573 {
574         InsetCode type = NO_CODE;
575         const Inset * content = nullptr;
576         const InsetCaption * caption = nullptr;
577         const InsetLabel * label = nullptr;
578
579         for (const auto & it : subfigure->paragraphs()) {
580                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
581                         const Inset * inset = it.getInset(posIn);
582                         if (inset) {
583                                 switch (inset->lyxCode()) {
584                                         case GRAPHICS_CODE:
585                                         case TABULAR_CODE:
586                                                 if (!content) {
587                                                         content = inset;
588                                                         type = inset->lyxCode();
589                                                 }
590                                                 break;
591                                         case CAPTION_CODE:
592                                                 if (!caption) {
593                                                         caption = dynamic_cast<const InsetCaption *>(inset);
594
595                                                         // A label often hides in a caption. Make a simplified version of the main loop.
596                                                         if (!label) {
597                                                                 for (const auto &cit : caption->paragraphs()) {
598                                                                         for (pos_type cposIn = 0; cposIn < cit.size(); ++cposIn) {
599                                                                                 const Inset *cinset = cit.getInset(posIn);
600                                                                                 if (cinset && cinset->lyxCode() == LABEL_CODE) {
601                                                                                         label = dynamic_cast<const InsetLabel *>(cinset);
602                                                                                         break;
603                                                                                 }
604                                                                         }
605
606                                                                         if (label)
607                                                                                 break;
608                                                                 }
609                                                         }
610                                                 }
611                                                 break;
612                                         case LABEL_CODE:
613                                                 if (!label)
614                                                         label = dynamic_cast<const InsetLabel *>(inset);
615                                                 break;
616                                         default:
617                                                 break;
618                                 }
619                         }
620                 }
621
622                 if (content && caption && label)
623                         break;
624         }
625
626         return std::make_tuple(type, content, caption, label);
627 }
628
629
630 void docbookSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
631                                            const InsetLabel * label, std::vector<const InsetCollapsible *> const & subfigures)
632 {
633         // Ensure there is no label output, it is supposed to be handled as xml:id.
634         OutputParams rpNoLabel = runparams;
635         if (label)
636                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
637
638         // First, open the formal group.
639         docstring attr = docstring();
640         if (label)
641                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
642
643         xs.startDivision(false);
644         xs << xml::StartTag("formalgroup", attr);
645         xs << xml::CR();
646
647         xs << xml::StartTag("title"); // Don't take attr here, the ID should only go in one place, not two.
648         if (caption) {
649                 caption->getCaptionAsDocBook(xs, rpNoLabel);
650         } else {
651                 xs << "No caption";
652                 // No caption has been detected, but this tag is required for the document to be valid DocBook.
653         }
654         xs << xml::EndTag("title");
655         xs << xml::CR();
656
657         // Deal with each subfigure individually. This should also deal with their caption and their label.
658         // This should be a recursive call to InsetFloat.
659         // An item in subfigure should either be an InsetBox containing an InsetFloat, or an InsetBox directly containing
660         // an image or a table, or directly an InsetFloat.
661         for (const InsetCollapsible * subfigure: subfigures) {
662                 if (subfigure == nullptr)
663                         continue;
664
665                 // The collapsible may already be a float (InsetFloat).
666                 if (dynamic_cast<const InsetFloat *>(subfigure)) {
667                         subfigure->docbook(xs, runparams);
668                         continue;
669                 }
670
671                 // Subfigures are in boxes, then in InsetFloat.
672                 {
673                         bool foundInsetFloat = false;
674                         for (const auto &it : subfigure->paragraphs()) {
675                                 for (pos_type posIn = 0; posIn < it.size(); ++posIn) {
676                                         const Inset *inset = it.getInset(posIn);
677                                         if (inset && inset->lyxCode() == FLOAT_CODE) {
678                                                 foundInsetFloat = true;
679                                                 inset->docbook(xs, runparams);
680                                                 break;
681                                         }
682                                 }
683
684                                 if (foundInsetFloat)
685                                         break;
686                         }
687                         if (foundInsetFloat)
688                                 continue;
689                 }
690
691                 // Subfigures are in boxes, then directly an image or a table. In that case, generate the whole content of the
692                 // InsetBox, but not the box container.
693                 // Impose some model on the subfigure: at most a caption, at most a label, exactly one figure or one table.
694                 {
695                         InsetCode stype = NO_CODE;
696                         const Inset * scontent = nullptr;
697                         const InsetCaption * scaption = nullptr;
698                         const InsetLabel * slabel = nullptr;
699
700                         std::tie(stype, scontent, scaption, slabel) = docbookParseHopelessSubfigure(subfigure);
701
702                         // If there is something, generate it. This is very much like docbookNoSubfigures, but many things
703                         // must be coded differently because there is no float.
704                         // TODO: some code is identical to Floating, like Floating::docbookTag or Floating::docbookCaption. How to reuse that code?
705                         if (scontent) {
706                                 // Floating::docbookCaption()
707                                 string docbook_caption = "caption"; // This is already correct for tables.
708                                 if (stype == GRAPHICS_CODE)
709                                         docbook_caption = "title";
710
711                                 // Floating::docbookTag() with hasTitle = true, as we are in formalgroup.
712                                 string stag = "float";
713                                 if (stype == GRAPHICS_CODE)
714                                         stag = "figure";
715                                 else if (stype == TABULAR_CODE)
716                                         stag = "table";
717
718                                 // Ensure there is no label output, it is supposed to be handled as xml:id.
719                                 if (slabel)
720                                         rpNoLabel.docbook_anchors_to_ignore.emplace(slabel->screenLabel());
721
722                                 // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
723                                 // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
724                                 OutputParams rpNoTitle = runparams;
725                                 rpNoTitle.docbook_in_float = true;
726                                 if (stype == TABULAR_CODE)
727                                         rpNoTitle.docbook_in_table = true;
728
729                                 // Organisation: <float> <title if any/> <contents without title/> </float>.
730                                 docstring sattr = docstring();
731                                 if (slabel)
732                                         sattr += "xml:id=\"" + xml::cleanID(slabel->screenLabel()) + "\"";
733                                 // No layout way of adding attributes, unlike the normal code path.
734
735                                 xs << xml::StartTag(stag, sattr);
736                                 xs << xml::CR();
737                                 xs << xml::StartTag(docbook_caption);
738                                 if (scaption)
739                                         scaption->getCaptionAsDocBook(xs, rpNoLabel);
740                                 else // Mandatory in formalgroup.
741                                         xs << "No caption detected";
742                                 xs << xml::EndTag(docbook_caption);
743                                 xs << xml::CR();
744                                 scontent->docbook(xs, rpNoTitle);
745                                 xs << xml::EndTag(stag);
746                                 xs << xml::CR();
747
748                                 // This subfigure could be generated.
749                                 continue;
750                         }
751                 }
752
753                 // If there is no InsetFloat in the inset, output a warning.
754                 xs << XMLStream::ESCAPE_NONE << "Error: no float found in the box. "
755                                                         "To use subfigures in DocBook, elements must be wrapped in a float "
756                                     "inset and have a title/caption.";
757                 // 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.
758
759                 // Recurse to generate as much content as possible (avoid any loss).
760                 subfigure->docbook(xs, runparams);
761         }
762
763         // Every subfigure is done: close the formal group.
764         xs << xml::EndTag("formalgroup");
765         xs << xml::CR();
766         xs.endDivision();
767 }
768
769
770 void docbookNoSubfigures(XMLStream & xs, OutputParams const & runparams, const InsetCaption * caption,
771                          const InsetLabel * label, Floating const & ftype, const InsetFloat * thisFloat)
772 {
773         string const &titleTag = ftype.docbookCaption();
774
775         // Ensure there is no label output, it is supposed to be handled as xml:id.
776         OutputParams rpNoLabel = runparams;
777         if (label)
778                 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
779
780         // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
781         // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
782         OutputParams rpNoTitle = runparams;
783         rpNoTitle.docbook_in_float = true;
784         if (ftype.docbookFloatType() == "table")
785                 rpNoTitle.docbook_in_table = true;
786
787         // Organisation: <float> <title if any/> <contents without title/> </float>.
788         docstring attr = docstring();
789         if (label)
790                 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
791         if (!ftype.docbookAttr().empty()) {
792                 if (!attr.empty())
793                         attr += " ";
794                 attr += from_utf8(ftype.docbookAttr());
795         }
796
797         xs << xml::StartTag(ftype.docbookTag(caption != nullptr), attr);
798         xs << xml::CR();
799         if (caption) {
800                 xs << xml::StartTag(titleTag);
801                 caption->getCaptionAsDocBook(xs, rpNoLabel);
802                 xs << xml::EndTag(titleTag);
803                 xs << xml::CR();
804         }
805         thisFloat->InsetText::docbook(xs, rpNoTitle);
806         xs << xml::EndTag(ftype.docbookTag(caption != nullptr));
807         xs << xml::CR();
808 }
809
810
811 void InsetFloat::docbook(XMLStream & xs, OutputParams const & runparams) const
812 {
813         // Determine whether the float has a title or not. For this, iterate through the paragraphs and look
814         // for an InsetCaption. Do the same for labels and subfigures.
815         // The caption and the label for each subfigure is handled by recursive calls.
816         const InsetCaption* caption = nullptr;
817         const InsetLabel* label = nullptr;
818         std::vector<const InsetCollapsible *> subfigures;
819
820         auto end = paragraphs().end();
821         for (auto it = paragraphs().begin(); it != end; ++it) {
822                 std::vector<const InsetCollapsible *> foundSubfigures = findSubfiguresInParagraph(*it);
823                 if (!foundSubfigures.empty()) {
824                         subfigures.reserve(subfigures.size() + foundSubfigures.size());
825                         subfigures.insert(subfigures.end(), foundSubfigures.begin(), foundSubfigures.end());
826                 }
827
828                 if (!caption)
829                         caption = findCaptionInParagraph(*it);
830                 if (!label)
831                         label = findLabelInParagraph(*it);
832         }
833
834         // Gather a few things from global environment that are shared between all following cases.
835         FloatList const &floats = buffer().params().documentClass().floats();
836         Floating const &ftype = floats.getType(params_.type);
837
838         // Switch on subfigures.
839         if (!subfigures.empty())
840                 docbookSubfigures(xs, runparams, caption, label, subfigures);
841         else
842                 docbookNoSubfigures(xs, runparams, caption, label, ftype, this);
843 }
844
845
846 bool InsetFloat::insetAllowed(InsetCode code) const
847 {
848         // The case that code == FLOAT_CODE is handled in Text3.cpp,
849         // because we need to know what type of float is meant.
850         switch(code) {
851         case WRAP_CODE:
852         case FOOT_CODE:
853         case MARGIN_CODE:
854                 return false;
855         default:
856                 return InsetCaptionable::insetAllowed(code);
857         }
858 }
859
860
861 void InsetFloat::setWide(bool w, bool update_label)
862 {
863         if (!buffer().params().documentClass().floats().allowsWide(params_.type))
864                 params_.wide = false;
865         else
866             params_.wide = w;
867         if (update_label)
868                 setNewLabel();
869 }
870
871
872 void InsetFloat::setSideways(bool s, bool update_label)
873 {
874         if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
875                 params_.sideways = false;
876         else
877                 params_.sideways = s;
878         if (update_label)
879                 setNewLabel();
880 }
881
882
883 void InsetFloat::setSubfloat(bool s, bool update_label)
884 {
885         params_.subfloat = s;
886         if (update_label)
887                 setNewLabel();
888 }
889
890
891 void InsetFloat::setNewLabel()
892 {
893         docstring lab = _("float: ");
894
895         if (params_.subfloat)
896                 lab = _("subfloat: ");
897
898         lab += floatName(params_.type);
899
900         FloatList const & floats = buffer().params().documentClass().floats();
901
902         if (params_.wide && floats.allowsWide(params_.type))
903                 lab += '*';
904
905         if (params_.sideways && floats.allowsSideways(params_.type))
906                 lab += _(" (sideways)");
907
908         setLabel(lab);
909 }
910
911
912 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
913 {
914         return !params_.subfloat && newtype != "Unnumbered";
915 }
916
917
918 TexString InsetFloat::getCaption(OutputParams const & runparams) const
919 {
920         InsetCaption const * ins = getCaptionInset();
921         if (ins == 0)
922                 return TexString();
923
924         otexstringstream os;
925         ins->getArgs(os, runparams);
926
927         if (!runparams.nice)
928                 // increase TexRow precision in non-nice mode
929                 os << safebreakln;
930         os << '[';
931         otexstringstream os2;
932         ins->getArgument(os2, runparams);
933         TexString ts = os2.release();
934         docstring & arg = ts.str;
935         // Protect ']'
936         if (arg.find(']') != docstring::npos)
937                 arg = '{' + arg + '}';
938         os << move(ts);
939         os << ']';
940         if (!runparams.nice)
941                 os << safebreakln;
942         return os.release();
943 }
944
945
946 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
947 {
948         params = InsetFloatParams();
949         if (in.empty())
950                 return;
951
952         istringstream data(in);
953         Lexer lex;
954         lex.setStream(data);
955         lex.setContext("InsetFloat::string2params");
956         params.read(lex);
957 }
958
959
960 string InsetFloat::params2string(InsetFloatParams const & params)
961 {
962         ostringstream data;
963         params.write(data);
964         return data.str();
965 }
966
967
968 } // namespace lyx