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.
16 #include <output_docbook.h>
20 #include "InsetCaption.h"
21 #include "InsetFloat.h"
22 #include "InsetGraphics.h"
23 #include "InsetLabel.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
30 #include "DispatchResult.h"
32 #include "FloatList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "output_xhtml.h"
38 #include "ParIterator.h"
40 #include "texstream.h"
41 #include "TextClass.h"
42 #include "InsetList.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
49 #include "frontends/Application.h"
52 using namespace lyx::support;
57 // With this inset it will be possible to support the latex package
58 // float.sty, and I am sure that with this and some additional support
59 // classes we can support similar functionality in other formats
61 // By using float.sty we will have the same handling for all floats, both
62 // for those already in existence (table and figure) and all user created
63 // ones¹. So suddenly we give the users the possibility of creating new
64 // kinds of floats on the fly. (and with a uniform look)
67 // \newfloat{type}{placement}{ext}[within]
68 // type - The "type" of the new class of floats, like program or
69 // algorithm. After the appropriate \newfloat, commands
70 // such as \begin{program} or \end{algorithm*} will be
72 // placement - The default placement for the given class of floats.
73 // They are like in standard LaTeX: t, b, p and h for top,
74 // bottom, page, and here, respectively. On top of that
75 // there is a new type, H, which does not really correspond
76 // to a float, since it means: put it "here" and nowhere else.
77 // Note, however that the H specifier is special and, because
78 // of implementation details cannot be used in the second
79 // argument of \newfloat.
80 // ext - The file name extension of an auxiliary file for the list
81 // of figures (or whatever). LaTeX writes the captions to
83 // within - This (optional) argument determines whether floats of this
84 // class will be numbered within some sectional unit of the
85 // document. For example, if within is equal to chapter, the
86 // floats will be numbered within chapters.
88 // style - plain, boxed, ruled
89 // \floatname{float}{floatname}
92 // \floatplacement{float}{placement}
95 // \restylefloat{float}
97 // \listof{type}{title}
100 // ¹ the algorithm float is defined using the float.sty package. Like this
101 // \floatstyle{ruled}
102 // \newfloat{algorithm}{htbp}{loa}[<sect>]
103 // \floatname{algorithm}{Algorithm}
105 // The intention is that floats should be definable from two places:
107 // - the "gui" (i.e. by the user)
109 // From layout files.
110 // This should only be done for floats defined in a documentclass and that
111 // does not need any additional packages. The two most known floats in this
112 // category is "table" and "figure". Floats defined in layout files are only
113 // stored in lyx files if the user modifies them.
116 // There should be a gui dialog (and also a collection of lyxfuncs) where
117 // the user can modify existing floats and/or create new ones.
119 // The individual floats will also have some settable
120 // variables: wide and placement.
124 //FIXME: why do we set in stone the type here?
125 InsetFloat::InsetFloat(Buffer * buf, string const & params_str)
126 : InsetCaptionable(buf)
128 string2params(params_str, params_);
129 setCaptionType(params_.type);
133 // Enforce equality of float type and caption type.
134 void InsetFloat::setCaptionType(std::string const & type)
136 InsetCaptionable::setCaptionType(type);
137 params_.type = captionType();
138 // check if the float type exists
139 if (buffer().params().documentClass().floats().typeExist(params_.type))
142 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
146 docstring InsetFloat::layoutName() const
148 return "Float:" + from_utf8(params_.type);
152 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
155 return InsetCaptionable::toolTip(bv, x, y);
157 OutputParams rp(&buffer().params().encoding());
158 return getCaptionText(rp);
162 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
164 switch (cmd.action()) {
166 case LFUN_INSET_MODIFY: {
167 InsetFloatParams params;
168 string2params(to_utf8(cmd.argument()), params);
169 cur.recordUndoInset(this);
171 // placement, wide and sideways are not used for subfloats
172 if (!params_.subfloat) {
173 params_.placement = params.placement;
174 params_.wide = params.wide;
175 params_.sideways = params.sideways;
177 params_.alignment = params.alignment;
179 if (params_.type != params.type)
180 setCaptionType(params.type);
181 // what we really want here is a TOC update, but that means
182 // a full buffer update
183 cur.forceBufferUpdate();
187 case LFUN_INSET_DIALOG_UPDATE: {
188 cur.bv().updateDialog("float", params2string(params()));
193 InsetCaptionable::doDispatch(cur, cmd);
199 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
200 FuncStatus & flag) const
202 switch (cmd.action()) {
204 case LFUN_INSET_MODIFY:
205 case LFUN_INSET_DIALOG_UPDATE:
206 flag.setEnabled(true);
209 case LFUN_INSET_SETTINGS:
210 if (InsetCaptionable::getStatus(cur, cmd, flag)) {
211 flag.setEnabled(flag.enabled() && !params_.subfloat);
216 case LFUN_NEWLINE_INSERT:
217 if (params_.subfloat) {
218 flag.setEnabled(false);
225 return InsetCaptionable::getStatus(cur, cmd, flag);
230 bool InsetFloat::hasSubCaptions(ParIterator const & it) const
232 return (it.innerInsetOfType(FLOAT_CODE) || it.innerInsetOfType(WRAP_CODE));
236 string InsetFloat::getAlignment() const
239 string const buf_alignment = buffer().params().float_alignment;
240 if (params_.alignment == "document"
241 && !buf_alignment.empty()) {
242 alignment = buf_alignment;
243 } else if (!params_.alignment.empty()
244 && params_.alignment != "class"
245 && params_.alignment != "document") {
246 alignment = params_.alignment;
252 LyXAlignment InsetFloat::contentAlignment() const
254 LyXAlignment align = LYX_ALIGN_NONE;
255 string alignment = getAlignment();
256 if (alignment == "left")
257 align = LYX_ALIGN_LEFT;
258 else if (alignment == "center")
259 align = LYX_ALIGN_CENTER;
260 else if (alignment == "right")
261 align = LYX_ALIGN_RIGHT;
267 void InsetFloatParams::write(ostream & os) const
270 // Better this than creating a parse error. This in fact happens in the
271 // parameters dialog via InsetFloatParams::params2string.
272 os << "senseless" << '\n';
276 if (!placement.empty())
277 os << "placement " << placement << "\n";
278 if (!alignment.empty())
279 os << "alignment " << alignment << "\n";
284 os << "wide false\n";
287 os << "sideways true\n";
289 os << "sideways false\n";
293 void InsetFloatParams::read(Lexer & lex)
295 lex.setContext("InsetFloatParams::read");
297 if (lex.checkFor("placement"))
299 if (lex.checkFor("alignment"))
301 lex >> "wide" >> wide;
302 lex >> "sideways" >> sideways;
306 void InsetFloat::write(ostream & os) const
310 InsetCaptionable::write(os);
314 void InsetFloat::read(Lexer & lex)
317 InsetCaptionable::read(lex);
318 setCaptionType(params_.type);
322 void InsetFloat::validate(LaTeXFeatures & features) const
324 if (support::contains(params_.placement, 'H'))
325 features.require("float");
327 if (params_.sideways)
328 features.require("rotfloat");
330 if (features.inFloat())
331 features.require("subfig");
333 if (features.inDeletedInset()) {
334 features.require("tikz");
335 features.require("ct-tikz-object-sout");
338 features.useFloat(params_.type, features.inFloat());
339 features.inFloat(true);
340 InsetCaptionable::validate(features);
341 features.inFloat(false);
345 docstring InsetFloat::xhtml(XMLStream & xs, OutputParams const & rp) const
347 FloatList const & floats = buffer().params().documentClass().floats();
348 Floating const & ftype = floats.getType(params_.type);
349 string const & htmltype = ftype.htmlTag();
350 string const & attr = ftype.htmlAttrib();
352 odocstringstream ods;
353 XMLStream newxs(ods);
354 newxs << xml::StartTag(htmltype, attr);
355 InsetText::XHTMLOptions const opts =
356 InsetText::WriteLabel | InsetText::WriteInnerTag;
357 docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
358 newxs << xml::EndTag(htmltype);
360 if (rp.inFloat == OutputParams::NONFLOAT) {
361 // In this case, this float needs to be deferred, but we'll put it
362 // before anything the text itself deferred.
363 deferred = ods.str() + '\n' + deferred;
365 // In this case, the whole thing is already being deferred, so
366 // we can write to the stream.
367 // Note that things will already have been escaped, so we do not
368 // want to escape them again.
369 xs << XMLStream::ESCAPE_NONE << ods.str();
375 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
377 if (runparams_in.inFloat != OutputParams::NONFLOAT) {
378 if (!paragraphs().empty() && !runparams_in.nice)
379 // improve TexRow precision in non-nice mode
382 if (runparams_in.moving_arg)
386 OutputParams rp = runparams_in;
387 rp.moving_arg = true;
388 os << getCaption(rp);
390 // The main argument is the contents of the float. This is not a moving argument.
391 rp.moving_arg = false;
392 rp.inFloat = OutputParams::SUBFLOAT;
393 InsetText::latex(os, rp);
398 OutputParams runparams(runparams_in);
399 runparams.inFloat = OutputParams::MAINFLOAT;
401 FloatList const & floats = buffer().params().documentClass().floats();
402 string tmptype = params_.type;
403 if (params_.sideways && floats.allowsSideways(params_.type))
404 tmptype = "sideways" + params_.type;
405 if (params_.wide && floats.allowsWide(params_.type)
406 && (!params_.sideways ||
407 params_.type == "figure" ||
408 params_.type == "table"))
410 // Figure out the float placement to use.
411 // From lowest to highest:
412 // - float default placement
413 // - document wide default placement
414 // - specific float placement
416 string const buf_placement = buffer().params().float_placement;
417 string const def_placement = floats.defaultPlacement(params_.type);
418 if (params_.placement == "document"
419 && !buf_placement.empty()
420 && buf_placement != def_placement) {
421 tmpplacement = buf_placement;
422 } else if (!params_.placement.empty()
423 && params_.placement != "document"
424 && params_.placement != def_placement) {
425 tmpplacement = params_.placement;
428 // Check if placement is allowed by this float
429 string const allowed_placement =
430 floats.allowedPlacement(params_.type);
432 string::const_iterator lit = tmpplacement.begin();
433 string::const_iterator end = tmpplacement.end();
434 for (; lit != end; ++lit) {
435 if (contains(allowed_placement, *lit))
439 // Force \begin{<floatname>} to appear in a new line.
440 os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
441 if (runparams.lastid != -1)
442 os.texrow().start(runparams.lastid, runparams.lastpos);
443 // We only output placement if different from the def_placement.
444 // sidewaysfloats always use their own page,
445 // therefore don't output the p option that is always set
446 if (!placement.empty()
447 && (!params_.sideways || from_ascii(placement) != "p"))
448 os << '[' << from_ascii(placement) << ']';
451 if (runparams.inDeletedInset) {
452 // This has to be done manually since we need it inside the float
453 OutputParams::CtObject ctobject = runparams.ctObject;
454 runparams.ctObject = OutputParams::CT_DISPLAYOBJECT;
455 Changes::latexMarkChange(os, buffer().params(), Change(Change::UNCHANGED),
456 Change(Change::DELETED), runparams);
457 runparams.ctObject = ctobject;
460 string alignment = getAlignment();
461 if (alignment == "left")
462 os << "\\raggedright" << breakln;
463 else if (alignment == "center")
464 os << "\\centering" << breakln;
465 else if (alignment == "right")
466 os << "\\raggedleft" << breakln;
468 InsetText::latex(os, runparams);
470 if (runparams.inDeletedInset)
473 // Force \end{<floatname>} to appear in a new line.
474 os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
478 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
480 os << '[' << buffer().B_("float") << ' '
481 << floatName(params_.type) << ":\n";
482 InsetText::plaintext(os, runparams, max_length);
485 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
489 std::vector<const InsetBox *> findSubfiguresInParagraph(const Paragraph &par)
492 // Don't make the hypothesis that all subfigures are in the same paragraph.
493 // Similarly, there may be several subfigures in the same paragraph (most likely case, based on the documentation).
494 // Any box is considered as a subfigure, even though the most likely case is \minipage.
495 std::vector<const InsetBox *> subfigures;
496 for (pos_type pos = 0; pos < par.size(); ++pos) {
497 const Inset *inset = par.getInset(pos);
500 if (const auto box = dynamic_cast<const InsetBox *>(inset))
501 subfigures.push_back(box);
507 const InsetLabel* findLabelInParagraph(const Paragraph &par)
509 for (pos_type pos = 0; pos < par.size(); ++pos) {
510 // If this inset is a subfigure, skip it.
511 const Inset *inset = par.getInset(pos);
512 if (dynamic_cast<const InsetBox *>(inset)) {
516 // Maybe an inset is directly a label, in which case no more work is needed.
517 if (inset && dynamic_cast<const InsetLabel *>(inset))
518 return dynamic_cast<const InsetLabel *>(inset);
520 // More likely, the label is hidden in an inset of a paragraph (only if a subtype of InsetText).
521 if (!dynamic_cast<const InsetText *>(inset))
524 auto insetAsText = dynamic_cast<const InsetText *>(inset);
525 auto itIn = insetAsText->paragraphs().begin();
526 auto endIn = insetAsText->paragraphs().end();
527 for (; itIn != endIn; ++itIn) {
528 for (pos_type posIn = 0; posIn < itIn->size(); ++posIn) {
529 const Inset *insetIn = itIn->getInset(posIn);
530 if (insetIn && dynamic_cast<const InsetLabel *>(insetIn)) {
531 return dynamic_cast<const InsetLabel *>(insetIn);
536 // Obviously, this solution does not scale with more levels of paragraphs-insets, but this should be enough.
543 const InsetCaption* findCaptionInParagraph(const Paragraph &par)
545 // Don't dive too deep, otherwise, this could be a subfigure caption.
546 for (pos_type pos = 0; pos < par.size(); ++pos) {
547 // If this inset is a subfigure, skip it.
548 const Inset *inset = par.getInset(pos);
549 if (dynamic_cast<const InsetBox *>(inset))
552 if (inset && dynamic_cast<const InsetCaption *>(inset))
553 return dynamic_cast<const InsetCaption *>(inset);
560 void InsetFloat::docbook(XMLStream & xs, OutputParams const & runparams) const
562 // Determine whether the float has a title or not. For this, iterate through the paragraphs and look
563 // for an InsetCaption. Do the same for labels and subfigures.
564 // The caption and the label for each subfigure is handled by recursive calls.
565 const InsetCaption* caption = nullptr;
566 const InsetLabel* label = nullptr;
567 std::vector<const InsetBox *> subfigures;
569 auto end = paragraphs().end();
570 for (auto it = paragraphs().begin(); it != end; ++it) {
571 std::vector<const InsetBox *> foundSubfigures = findSubfiguresInParagraph(*it);
572 if (!foundSubfigures.empty()) {
573 subfigures.reserve(subfigures.size() + foundSubfigures.size());
574 subfigures.insert(subfigures.end(), foundSubfigures.begin(), foundSubfigures.end());
578 caption = findCaptionInParagraph(*it);
580 label = findLabelInParagraph(*it);
583 // Gather a few things from global environment that are shared between all following cases.
584 FloatList const &floats = buffer().params().documentClass().floats();
585 Floating const &ftype = floats.getType(params_.type);
586 string const &titleTag = ftype.docbookCaption();
588 // Ensure there is no label output, it is supposed to be handled as xml:id.
589 OutputParams rpNoLabel = runparams;
591 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
593 // Ensure the float does not output its caption, as it is handled here (DocBook mandates a specific place for
594 // captions, they cannot appear at the end of the float, albeit LyX is happy with that).
595 OutputParams rpNoTitle = runparams;
596 rpNoTitle.docbook_in_float = true;
598 // Deal with subfigures.
599 if (!subfigures.empty()) {
600 // First, open the formal group.
601 docstring attr = docstring();
603 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
605 xs.startDivision(false);
606 xs << xml::StartTag("formalgroup", attr);
609 xs << xml::StartTag("title", attr);
611 caption->getCaptionAsDocBook(xs, rpNoLabel);
614 // No caption has been detected, but this tag is required for the document to be valid DocBook.
616 xs << xml::EndTag("title");
619 // Deal with each subfigure individually. This should also deal with their caption and their label.
620 // This should be a recursive call to InsetFloat.
621 for (const InsetBox *subfigure: subfigures) {
622 // If there is no InsetFloat in the paragraphs, output a warning.
623 bool foundInsetFloat = false;
624 for (auto it = subfigure->paragraphs().begin(); it != subfigure->paragraphs().end(); ++it) {
625 for (pos_type posIn = 0; posIn < it->size(); ++posIn) {
626 const Inset *inset = it->getInset(posIn);
627 if (inset && dynamic_cast<const InsetFloat*>(inset)) {
628 foundInsetFloat = true;
637 if (!foundInsetFloat)
638 xs << XMLStream::ESCAPE_NONE << "Error: no float found in the box. "
639 "To use subfigures in DocBook, elements must be wrapped in a float "
640 "inset and have a title/caption.";
641 // 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.
644 subfigure->docbook(xs, runparams);
647 // Every subfigure is done: close the formal group.
648 xs << xml::EndTag("formalgroup");
653 // Here, ensured not to have subfigures.
655 // Organisation: <float> <title if any/> <contents without title/> </float>
656 docstring attr = docstring();
658 attr += "xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
659 if (!ftype.docbookAttr().empty()) {
662 attr += from_utf8(ftype.docbookAttr());
665 xs << xml::StartTag(ftype.docbookTag(caption != nullptr), attr);
667 if (caption != nullptr) {
668 xs << xml::StartTag(titleTag);
669 caption->getCaptionAsDocBook(xs, rpNoLabel);
670 xs << xml::EndTag(titleTag);
673 InsetText::docbook(xs, rpNoTitle);
674 xs << xml::EndTag(ftype.docbookTag(caption != nullptr));
679 bool InsetFloat::insetAllowed(InsetCode code) const
681 // The case that code == FLOAT_CODE is handled in Text3.cpp,
682 // because we need to know what type of float is meant.
689 return InsetCaptionable::insetAllowed(code);
694 void InsetFloat::setWide(bool w, bool update_label)
696 if (!buffer().params().documentClass().floats().allowsWide(params_.type))
697 params_.wide = false;
705 void InsetFloat::setSideways(bool s, bool update_label)
707 if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
708 params_.sideways = false;
710 params_.sideways = s;
716 void InsetFloat::setSubfloat(bool s, bool update_label)
718 params_.subfloat = s;
724 void InsetFloat::setNewLabel()
726 docstring lab = _("float: ");
728 if (params_.subfloat)
729 lab = _("subfloat: ");
731 lab += floatName(params_.type);
733 FloatList const & floats = buffer().params().documentClass().floats();
735 if (params_.wide && floats.allowsWide(params_.type))
738 if (params_.sideways && floats.allowsSideways(params_.type))
739 lab += _(" (sideways)");
745 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
747 return !params_.subfloat && newtype != "Unnumbered";
751 TexString InsetFloat::getCaption(OutputParams const & runparams) const
753 InsetCaption const * ins = getCaptionInset();
758 ins->getArgs(os, runparams);
761 // increase TexRow precision in non-nice mode
764 otexstringstream os2;
765 ins->getArgument(os2, runparams);
766 TexString ts = os2.release();
767 docstring & arg = ts.str;
769 if (arg.find(']') != docstring::npos)
770 arg = '{' + arg + '}';
779 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
781 params = InsetFloatParams();
785 istringstream data(in);
788 lex.setContext("InsetFloat::string2params");
793 string InsetFloat::params2string(InsetFloatParams const & params)