3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Jürgen Spitzmüller
10 * Full author contact details are available in file CREDITS.
17 #include "InsetCaption.h"
18 #include "InsetFloat.h"
19 #include "InsetGraphics.h"
20 #include "InsetLabel.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
27 #include "DispatchResult.h"
29 #include "FloatList.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
32 #include "LaTeXFeatures.h"
35 #include "output_docbook.h"
36 #include "output_xhtml.h"
37 #include "ParIterator.h"
39 #include "texstream.h"
40 #include "TextClass.h"
41 #include "InsetList.h"
43 #include "support/debug.h"
44 #include "support/docstream.h"
45 #include "support/gettext.h"
46 #include "support/lstrings.h"
48 #include "frontends/Application.h"
51 using namespace lyx::support;
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
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)
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
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
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.
87 // style - plain, boxed, ruled
88 // \floatname{float}{floatname}
91 // \floatplacement{float}{placement}
94 // \restylefloat{float}
96 // \listof{type}{title}
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}
104 // The intention is that floats should be definable from two places:
106 // - the "gui" (i.e. by the user)
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.
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.
118 // The individual floats will also have some settable
119 // variables: wide and placement.
123 //FIXME: why do we set in stone the type here?
124 InsetFloat::InsetFloat(Buffer * buf, string const & params_str)
125 : InsetCaptionable(buf)
127 string2params(params_str, params_);
128 setCaptionType(params_.type);
132 // Enforce equality of float type and caption type.
133 void InsetFloat::setCaptionType(std::string const & type)
135 InsetCaptionable::setCaptionType(type);
136 params_.type = captionType();
137 // check if the float type exists
138 if (buffer().params().documentClass().floats().typeExist(params_.type))
141 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
145 docstring InsetFloat::layoutName() const
147 return "Float:" + from_utf8(params_.type);
151 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
154 return InsetCaptionable::toolTip(bv, x, y);
156 OutputParams rp(&buffer().params().encoding());
157 return getCaptionText(rp);
161 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
163 switch (cmd.action()) {
165 case LFUN_INSET_MODIFY: {
166 InsetFloatParams params;
167 string2params(to_utf8(cmd.argument()), params);
168 cur.recordUndoInset(this);
170 // placement, wide and sideways are not used for subfloats
171 if (!params_.subfloat) {
172 params_.placement = params.placement;
173 params_.wide = params.wide;
174 params_.sideways = params.sideways;
176 params_.alignment = params.alignment;
178 if (params_.type != params.type)
179 setCaptionType(params.type);
180 // what we really want here is a TOC update, but that means
181 // a full buffer update
182 cur.forceBufferUpdate();
186 case LFUN_INSET_DIALOG_UPDATE: {
187 cur.bv().updateDialog("float", params2string(params()));
192 InsetCaptionable::doDispatch(cur, cmd);
198 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
199 FuncStatus & flag) const
201 switch (cmd.action()) {
203 case LFUN_INSET_MODIFY:
204 case LFUN_INSET_DIALOG_UPDATE:
205 flag.setEnabled(true);
208 case LFUN_INSET_SETTINGS:
209 if (InsetCaptionable::getStatus(cur, cmd, flag)) {
210 flag.setEnabled(flag.enabled() && !params_.subfloat);
215 case LFUN_NEWLINE_INSERT:
216 if (params_.subfloat) {
217 flag.setEnabled(false);
224 return InsetCaptionable::getStatus(cur, cmd, flag);
229 bool InsetFloat::hasSubCaptions(ParIterator const & it) const
231 return (it.innerInsetOfType(FLOAT_CODE) || it.innerInsetOfType(WRAP_CODE));
235 string InsetFloat::getAlignment() const
238 string const buf_alignment = buffer().params().float_alignment;
239 if (params_.alignment == "document"
240 && !buf_alignment.empty()) {
241 alignment = buf_alignment;
242 } else if (!params_.alignment.empty()
243 && params_.alignment != "class"
244 && params_.alignment != "document") {
245 alignment = params_.alignment;
251 LyXAlignment InsetFloat::contentAlignment() const
253 LyXAlignment align = LYX_ALIGN_NONE;
254 string alignment = getAlignment();
255 if (alignment == "left")
256 align = LYX_ALIGN_LEFT;
257 else if (alignment == "center")
258 align = LYX_ALIGN_CENTER;
259 else if (alignment == "right")
260 align = LYX_ALIGN_RIGHT;
266 void InsetFloatParams::write(ostream & os) const
269 // Better this than creating a parse error. This in fact happens in the
270 // parameters dialog via InsetFloatParams::params2string.
271 os << "senseless" << '\n';
275 if (!placement.empty())
276 os << "placement " << placement << "\n";
277 if (!alignment.empty())
278 os << "alignment " << alignment << "\n";
283 os << "wide false\n";
286 os << "sideways true\n";
288 os << "sideways false\n";
292 void InsetFloatParams::read(Lexer & lex)
294 lex.setContext("InsetFloatParams::read");
296 if (lex.checkFor("placement"))
298 if (lex.checkFor("alignment"))
300 lex >> "wide" >> wide;
301 lex >> "sideways" >> sideways;
305 void InsetFloat::write(ostream & os) const
309 InsetCaptionable::write(os);
313 void InsetFloat::read(Lexer & lex)
316 InsetCaptionable::read(lex);
317 setCaptionType(params_.type);
321 void InsetFloat::validate(LaTeXFeatures & features) const
323 if (support::contains(params_.placement, 'H'))
324 features.require("float");
326 if (params_.sideways)
327 features.require("rotfloat");
329 if (features.inFloat())
330 features.require("subfig");
332 if (features.inDeletedInset()) {
333 features.require("tikz");
334 features.require("ct-tikz-object-sout");
337 features.useFloat(params_.type, features.inFloat());
338 features.inFloat(true);
339 InsetCaptionable::validate(features);
340 features.inFloat(false);
344 docstring InsetFloat::xhtml(XMLStream & xs, OutputParams const & rp) const
346 FloatList const & floats = buffer().params().documentClass().floats();
347 Floating const & ftype = floats.getType(params_.type);
348 string const & htmltype = ftype.htmlTag();
349 string const & attr = ftype.htmlAttrib();
351 odocstringstream ods;
352 XMLStream newxs(ods);
353 newxs << xml::StartTag(htmltype, attr);
354 InsetText::XHTMLOptions const opts =
355 InsetText::WriteLabel | InsetText::WriteInnerTag;
356 docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
357 newxs << xml::EndTag(htmltype);
359 if (rp.inFloat == OutputParams::NONFLOAT) {
360 // In this case, this float needs to be deferred, but we'll put it
361 // before anything the text itself deferred.
362 deferred = ods.str() + '\n' + deferred;
364 // In this case, the whole thing is already being deferred, so
365 // we can write to the stream.
366 // Note that things will already have been escaped, so we do not
367 // want to escape them again.
368 xs << XMLStream::ESCAPE_NONE << ods.str();
374 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
376 if (runparams_in.inFloat != OutputParams::NONFLOAT) {
377 if (!paragraphs().empty() && !runparams_in.nice)
378 // improve TexRow precision in non-nice mode
381 if (runparams_in.moving_arg)
385 OutputParams rp = runparams_in;
386 rp.moving_arg = true;
387 os << getCaption(rp);
389 // The main argument is the contents of the float. This is not a moving argument.
390 rp.moving_arg = false;
391 rp.inFloat = OutputParams::SUBFLOAT;
392 InsetText::latex(os, rp);
397 OutputParams runparams(runparams_in);
398 runparams.inFloat = OutputParams::MAINFLOAT;
400 FloatList const & floats = buffer().params().documentClass().floats();
401 string tmptype = params_.type;
402 if (params_.sideways && floats.allowsSideways(params_.type))
403 tmptype = "sideways" + params_.type;
404 if (params_.wide && floats.allowsWide(params_.type)
405 && (!params_.sideways ||
406 params_.type == "figure" ||
407 params_.type == "table"))
409 // Figure out the float placement to use.
410 // From lowest to highest:
411 // - float default placement
412 // - document wide default placement
413 // - specific float placement
415 string const buf_placement = buffer().params().float_placement;
416 string const def_placement = floats.defaultPlacement(params_.type);
417 if (params_.placement == "document"
418 && !buf_placement.empty()
419 && buf_placement != def_placement) {
420 tmpplacement = buf_placement;
421 } else if (!params_.placement.empty()
422 && params_.placement != "document"
423 && params_.placement != def_placement) {
424 tmpplacement = params_.placement;
427 // Check if placement is allowed by this float
428 string const allowed_placement =
429 floats.allowedPlacement(params_.type);
431 string::const_iterator lit = tmpplacement.begin();
432 string::const_iterator end = tmpplacement.end();
433 for (; lit != end; ++lit) {
434 if (contains(allowed_placement, *lit))
438 // Force \begin{<floatname>} to appear in a new line.
439 os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
440 if (runparams.lastid != -1)
441 os.texrow().start(runparams.lastid, runparams.lastpos);
442 // We only output placement if different from the def_placement.
443 // sidewaysfloats always use their own page,
444 // therefore don't output the p option that is always set
445 if (!placement.empty()
446 && (!params_.sideways || from_ascii(placement) != "p"))
447 os << '[' << from_ascii(placement) << ']';
450 if (runparams.inDeletedInset) {
451 // This has to be done manually since we need it inside the float
452 OutputParams::CtObject ctobject = runparams.ctObject;
453 runparams.ctObject = OutputParams::CT_DISPLAYOBJECT;
454 Changes::latexMarkChange(os, buffer().params(), Change(Change::UNCHANGED),
455 Change(Change::DELETED), runparams);
456 runparams.ctObject = ctobject;
459 string alignment = getAlignment();
460 if (alignment == "left")
461 os << "\\raggedright" << breakln;
462 else if (alignment == "center")
463 os << "\\centering" << breakln;
464 else if (alignment == "right")
465 os << "\\raggedleft" << breakln;
467 InsetText::latex(os, runparams);
469 if (runparams.inDeletedInset)
472 // Force \end{<floatname>} to appear in a new line.
473 os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
477 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
479 os << '[' << buffer().B_("float") << ' '
480 << floatName(params_.type) << ":\n";
481 InsetText::plaintext(os, runparams, max_length);
484 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
488 std::vector<const InsetBox *> findSubfiguresInParagraph(const Paragraph &par)
491 // Don't make the hypothesis that all subfigures are in the same paragraph.
492 // Similarly, there may be several subfigures in the same paragraph (most likely case, based on the documentation).
493 // Any box is considered as a subfigure, even though the most likely case is \minipage.
494 std::vector<const InsetBox *> subfigures;
495 for (pos_type pos = 0; pos < par.size(); ++pos) {
496 const Inset *inset = par.getInset(pos);
499 if (const auto box = dynamic_cast<const InsetBox *>(inset))
500 subfigures.push_back(box);
506 const InsetLabel* findLabelInParagraph(const Paragraph &par)
508 for (pos_type pos = 0; pos < par.size(); ++pos) {
509 // If this inset is a subfigure, skip it.
510 const Inset *inset = par.getInset(pos);
511 if (dynamic_cast<const InsetBox *>(inset)) {
515 // Maybe an inset is directly a label, in which case no more work is needed.
516 if (inset && dynamic_cast<const InsetLabel *>(inset))
517 return dynamic_cast<const InsetLabel *>(inset);
519 // More likely, the label is hidden in an inset of a paragraph (only if a subtype of InsetText).
520 if (!dynamic_cast<const InsetText *>(inset))
523 auto insetAsText = dynamic_cast<const InsetText *>(inset);
524 auto itIn = insetAsText->paragraphs().begin();
525 auto endIn = insetAsText->paragraphs().end();
526 for (; itIn != endIn; ++itIn) {
527 for (pos_type posIn = 0; posIn < itIn->size(); ++posIn) {
528 const Inset *insetIn = itIn->getInset(posIn);
529 if (insetIn && dynamic_cast<const InsetLabel *>(insetIn)) {
530 return dynamic_cast<const InsetLabel *>(insetIn);
535 // Obviously, this solution does not scale with more levels of paragraphs-insets, but this should be enough.
542 const InsetCaption* findCaptionInParagraph(const Paragraph &par)
544 // Don't dive too deep, otherwise, this could be a subfigure caption.
545 for (pos_type pos = 0; pos < par.size(); ++pos) {
546 // If this inset is a subfigure, skip it.
547 const Inset *inset = par.getInset(pos);
548 if (dynamic_cast<const InsetBox *>(inset))
551 if (inset && dynamic_cast<const InsetCaption *>(inset))
552 return dynamic_cast<const InsetCaption *>(inset);
559 void InsetFloat::docbook(XMLStream & xs, OutputParams const & runparams) const
561 // Determine whether the float has a title or not. For this, iterate through the paragraphs and look
562 // for an InsetCaption. Do the same for labels and subfigures.
563 // The caption and the label for each subfigure is handled by recursive calls.
564 const InsetCaption* caption = nullptr;
565 const InsetLabel* label = nullptr;
566 std::vector<const InsetBox *> subfigures;
568 auto end = paragraphs().end();
569 for (auto it = paragraphs().begin(); it != end; ++it) {
570 std::vector<const InsetBox *> foundSubfigures = findSubfiguresInParagraph(*it);
571 if (!foundSubfigures.empty()) {
572 subfigures.reserve(subfigures.size() + foundSubfigures.size());
573 subfigures.insert(subfigures.end(), foundSubfigures.begin(), foundSubfigures.end());
577 caption = findCaptionInParagraph(*it);
579 label = findLabelInParagraph(*it);
582 // Gather a few things from global environment that are shared between all following cases.
583 FloatList const &floats = buffer().params().documentClass().floats();
584 Floating const &ftype = floats.getType(params_.type);
585 string const &titleTag = ftype.docbookCaption();
587 // Ensure there is no label output, it is supposed to be handled as xml:id.
588 OutputParams rpNoLabel = runparams;
590 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
592 // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
593 // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
594 OutputParams rpNoTitle = runparams;
595 rpNoTitle.docbook_in_float = true;
597 // Deal with subfigures.
598 if (!subfigures.empty()) {
599 // First, open the formal group.
600 docstring attr = docstring();
602 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
604 xs.startDivision(false);
605 xs << xml::StartTag("formalgroup", attr);
608 xs << xml::StartTag("title", attr);
610 caption->getCaptionAsDocBook(xs, rpNoLabel);
613 // No caption has been detected, but this tag is required for the document to be valid DocBook.
615 xs << xml::EndTag("title");
618 // Deal with each subfigure individually. This should also deal with their caption and their label.
619 // This should be a recursive call to InsetFloat.
620 for (const InsetBox *subfigure: subfigures) {
621 // If there is no InsetFloat in the paragraphs, output a warning.
622 bool foundInsetFloat = false;
623 for (auto it = subfigure->paragraphs().begin(); it != subfigure->paragraphs().end(); ++it) {
624 for (pos_type posIn = 0; posIn < it->size(); ++posIn) {
625 const Inset *inset = it->getInset(posIn);
626 if (inset && dynamic_cast<const InsetFloat*>(inset)) {
627 foundInsetFloat = true;
636 if (!foundInsetFloat)
637 xs << XMLStream::ESCAPE_NONE << "Error: no float found in the box. "
638 "To use subfigures in DocBook, elements must be wrapped in a float "
639 "inset and have a title/caption.";
640 // 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.
643 subfigure->docbook(xs, runparams);
646 // Every subfigure is done: close the formal group.
647 xs << xml::EndTag("formalgroup");
652 // Here, ensured not to have subfigures.
654 // Organisation: <float> <title if any/> <contents without title/> </float>
655 docstring attr = docstring();
657 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
658 if (!ftype.docbookAttr().empty()) {
661 attr += from_utf8(ftype.docbookAttr());
664 xs << xml::StartTag(ftype.docbookTag(caption != nullptr), attr);
666 if (caption != nullptr) {
667 xs << xml::StartTag(titleTag);
668 caption->getCaptionAsDocBook(xs, rpNoLabel);
669 xs << xml::EndTag(titleTag);
672 InsetText::docbook(xs, rpNoTitle);
673 xs << xml::EndTag(ftype.docbookTag(caption != nullptr));
678 bool InsetFloat::insetAllowed(InsetCode code) const
680 // The case that code == FLOAT_CODE is handled in Text3.cpp,
681 // because we need to know what type of float is meant.
688 return InsetCaptionable::insetAllowed(code);
693 void InsetFloat::setWide(bool w, bool update_label)
695 if (!buffer().params().documentClass().floats().allowsWide(params_.type))
696 params_.wide = false;
704 void InsetFloat::setSideways(bool s, bool update_label)
706 if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
707 params_.sideways = false;
709 params_.sideways = s;
715 void InsetFloat::setSubfloat(bool s, bool update_label)
717 params_.subfloat = s;
723 void InsetFloat::setNewLabel()
725 docstring lab = _("float: ");
727 if (params_.subfloat)
728 lab = _("subfloat: ");
730 lab += floatName(params_.type);
732 FloatList const & floats = buffer().params().documentClass().floats();
734 if (params_.wide && floats.allowsWide(params_.type))
737 if (params_.sideways && floats.allowsSideways(params_.type))
738 lab += _(" (sideways)");
744 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
746 return !params_.subfloat && newtype != "Unnumbered";
750 TexString InsetFloat::getCaption(OutputParams const & runparams) const
752 InsetCaption const * ins = getCaptionInset();
757 ins->getArgs(os, runparams);
760 // increase TexRow precision in non-nice mode
763 otexstringstream os2;
764 ins->getArgument(os2, runparams);
765 TexString ts = os2.release();
766 docstring & arg = ts.str;
768 if (arg.find(']') != docstring::npos)
769 arg = '{' + arg + '}';
778 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
780 params = InsetFloatParams();
784 istringstream data(in);
787 lex.setContext("InsetFloat::string2params");
792 string InsetFloat::params2string(InsetFloatParams const & params)