]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
prepare Qt 5.6 builds
[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 #include "InsetCaption.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Counters.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "Floating.h"
25 #include "FloatList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "Lexer.h"
30 #include "output_xhtml.h"
31 #include "ParIterator.h"
32 #include "TextClass.h"
33
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38
39 #include "frontends/Application.h"
40
41 using namespace std;
42 using namespace lyx::support;
43
44
45 namespace lyx {
46
47 // With this inset it will be possible to support the latex package
48 // float.sty, and I am sure that with this and some additional support
49 // classes we can support similar functionality in other formats
50 // (read DocBook).
51 // By using float.sty we will have the same handling for all floats, both
52 // for those already in existance (table and figure) and all user created
53 // ones¹. So suddenly we give the users the possibility of creating new
54 // kinds of floats on the fly. (and with a uniform look)
55 //
56 // API to float.sty:
57 //   \newfloat{type}{placement}{ext}[within]
58 //     type      - The "type" of the new class of floats, like program or
59 //                 algorithm. After the appropriate \newfloat, commands
60 //                 such as \begin{program} or \end{algorithm*} will be
61 //                 available.
62 //     placement - The default placement for the given class of floats.
63 //                 They are like in standard LaTeX: t, b, p and h for top,
64 //                 bottom, page, and here, respectively. On top of that
65 //                 there is a new type, H, which does not really correspond
66 //                 to a float, since it means: put it "here" and nowhere else.
67 //                 Note, however that the H specifier is special and, because
68 //                 of implementation details cannot be used in the second
69 //                 argument of \newfloat.
70 //     ext       - The file name extension of an auxiliary file for the list
71 //                 of figures (or whatever). LaTeX writes the captions to
72 //                 this file.
73 //     within    - This (optional) argument determines whether floats of this
74 //                 class will be numbered within some sectional unit of the
75 //                 document. For example, if within is equal to chapter, the
76 //                 floats will be numbered within chapters.
77 //   \floatstyle{style}
78 //     style -  plain, boxed, ruled
79 //   \floatname{float}{floatname}
80 //     float     -
81 //     floatname -
82 //   \floatplacement{float}{placement}
83 //     float     -
84 //     placement -
85 //   \restylefloat{float}
86 //     float -
87 //   \listof{type}{title}
88 //     title -
89
90 // ¹ the algorithm float is defined using the float.sty package. Like this
91 //   \floatstyle{ruled}
92 //   \newfloat{algorithm}{htbp}{loa}[<sect>]
93 //   \floatname{algorithm}{Algorithm}
94 //
95 // The intention is that floats should be definable from two places:
96 //          - layout files
97 //          - the "gui" (i.e. by the user)
98 //
99 // From layout files.
100 // This should only be done for floats defined in a documentclass and that
101 // does not need any additional packages. The two most known floats in this
102 // category is "table" and "figure". Floats defined in layout files are only
103 // stored in lyx files if the user modifies them.
104 //
105 // By the user.
106 // There should be a gui dialog (and also a collection of lyxfuncs) where
107 // the user can modify existing floats and/or create new ones.
108 //
109 // The individual floats will also have some settable
110 // variables: wide and placement.
111 //
112 // Lgb
113
114 //FIXME: why do we set in stone the type here?
115 InsetFloat::InsetFloat(Buffer * buf, string params_str)
116         : InsetCaptionable(buf)
117 {
118         string2params(params_str, params_);
119         setCaptionType(params_.type);
120 }
121
122
123 // Enforce equality of float type and caption type.
124 void InsetFloat::setCaptionType(std::string const & type)
125 {
126         InsetCaptionable::setCaptionType(type); 
127         params_.type = captionType();
128         // check if the float type exists
129         if (buffer().params().documentClass().floats().typeExist(params_.type))
130                 setLabel(_("float: ") + floatName(params_.type));
131         else
132                 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
133 }
134
135
136 docstring InsetFloat::layoutName() const
137
138         return "Float:" + from_utf8(params_.type);
139 }
140
141
142 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
143 {
144         if (isOpen(bv))
145                 return InsetCaptionable::toolTip(bv, x, y);
146
147         OutputParams rp(&buffer().params().encoding());
148         return getCaptionText(rp);
149 }
150
151
152 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
153 {
154         switch (cmd.action()) {
155
156         case LFUN_INSET_MODIFY: {
157                 InsetFloatParams params;
158                 string2params(to_utf8(cmd.argument()), params);
159                 cur.recordUndoInset(this);
160
161                 // placement, wide and sideways are not used for subfloats
162                 if (!params_.subfloat) {
163                         params_.placement = params.placement;
164                         params_.wide      = params.wide;
165                         params_.sideways  = params.sideways;
166                 }
167                 setNewLabel();
168                 if (params_.type != params.type)
169                         setCaptionType(params.type);
170                 // what we really want here is a TOC update, but that means
171                 // a full buffer update
172                 cur.forceBufferUpdate();
173                 break;
174         }
175
176         case LFUN_INSET_DIALOG_UPDATE: {
177                 cur.bv().updateDialog("float", params2string(params()));
178                 break;
179         }
180
181         default:
182                 InsetCaptionable::doDispatch(cur, cmd);
183                 break;
184         }
185 }
186
187
188 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
189                 FuncStatus & flag) const
190 {
191         switch (cmd.action()) {
192
193         case LFUN_INSET_MODIFY:
194         case LFUN_INSET_DIALOG_UPDATE:
195                 flag.setEnabled(true);
196                 return true;
197
198         case LFUN_INSET_SETTINGS:
199                 if (InsetCaptionable::getStatus(cur, cmd, flag)) {
200                         flag.setEnabled(flag.enabled() && !params_.subfloat);
201                         return true;
202                 } else
203                         return false;
204         
205         case LFUN_NEWLINE_INSERT:
206                 if (params_.subfloat) {
207                         flag.setEnabled(false);
208                         return true;
209                 }
210
211         default:
212                 return InsetCaptionable::getStatus(cur, cmd, flag);
213         }
214 }
215
216
217 bool InsetFloat::hasSubCaptions(ParIterator const & it) const
218 {
219         return (it.innerInsetOfType(FLOAT_CODE) || it.innerInsetOfType(WRAP_CODE));
220 }
221
222
223 void InsetFloatParams::write(ostream & os) const
224 {
225         if (type.empty()) {
226                 // Better this than creating a parse error. This in fact happens in the
227                 // parameters dialog via InsetFloatParams::params2string.
228                 os << "senseless" << '\n';
229         } else
230                 os << type << '\n';
231
232         if (!placement.empty())
233                 os << "placement " << placement << "\n";
234
235         if (wide)
236                 os << "wide true\n";
237         else
238                 os << "wide false\n";
239
240         if (sideways)
241                 os << "sideways true\n";
242         else
243                 os << "sideways false\n";
244 }
245
246
247 void InsetFloatParams::read(Lexer & lex)
248 {
249         lex.setContext("InsetFloatParams::read");
250         lex >> type;
251         if (lex.checkFor("placement"))
252                 lex >> placement;
253         lex >> "wide" >> wide;
254         lex >> "sideways" >> sideways;
255 }
256
257
258 void InsetFloat::write(ostream & os) const
259 {
260         os << "Float ";
261         params_.write(os);
262         InsetCaptionable::write(os);
263 }
264
265
266 void InsetFloat::read(Lexer & lex)
267 {
268         params_.read(lex);
269         InsetCaptionable::read(lex);
270         setCaptionType(params_.type);
271 }
272
273
274 void InsetFloat::validate(LaTeXFeatures & features) const
275 {
276         if (support::contains(params_.placement, 'H'))
277                 features.require("float");
278
279         if (params_.sideways)
280                 features.require("rotfloat");
281
282         if (features.inFloat())
283                 features.require("subfig");
284
285         features.useFloat(params_.type, features.inFloat());
286         features.inFloat(true);
287         InsetCaptionable::validate(features);
288         features.inFloat(false);
289 }
290
291
292 docstring InsetFloat::xhtml(XHTMLStream & xs, OutputParams const & rp) const
293 {
294         FloatList const & floats = buffer().params().documentClass().floats();
295         Floating const & ftype = floats.getType(params_.type);
296         string const & htmltype = ftype.htmlTag();
297         string const & attr = ftype.htmlAttrib();
298
299         odocstringstream ods;
300         XHTMLStream newxs(ods);
301         newxs << html::StartTag(htmltype, attr);
302         InsetText::XHTMLOptions const opts = 
303                 InsetText::WriteLabel | InsetText::WriteInnerTag;
304         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
305         newxs << html::EndTag(htmltype);
306
307         if (rp.inFloat == OutputParams::NONFLOAT)
308                 // In this case, this float needs to be deferred, but we'll put it
309                 // before anything the text itself deferred.
310                 deferred = ods.str() + '\n' + deferred;
311         else 
312                 // In this case, the whole thing is already being deferred, so
313                 // we can write to the stream.
314                 // Note that things will already have been escaped, so we do not 
315                 // want to escape them again.
316                 xs << XHTMLStream::ESCAPE_NONE << ods.str();
317         return deferred;
318 }
319
320
321 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
322 {
323         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
324                 if (runparams_in.moving_arg)
325                         os << "\\protect";
326                 os << "\\subfloat";
327
328                 OutputParams rp = runparams_in;
329                 rp.moving_arg = true;
330                 getCaption(os, rp);
331                 os << '{';
332                 // The main argument is the contents of the float. This is not a moving argument.
333                 if (!paragraphs().empty())
334                         os.texrow().forceStart(paragraphs()[0].id(), 0);
335                 rp.moving_arg = false;
336                 rp.inFloat = OutputParams::SUBFLOAT;
337                 InsetText::latex(os, rp);
338                 os << "}";
339
340                 return;
341         }
342         OutputParams runparams(runparams_in);
343         runparams.inFloat = OutputParams::MAINFLOAT;
344
345         FloatList const & floats = buffer().params().documentClass().floats();
346         string tmptype = params_.type;
347         if (params_.sideways && floats.allowsSideways(params_.type))
348                 tmptype = "sideways" + params_.type;
349         if (params_.wide && floats.allowsWide(params_.type)
350                 && (!params_.sideways ||
351                      params_.type == "figure" ||
352                      params_.type == "table"))
353                 tmptype += "*";
354         // Figure out the float placement to use.
355         // From lowest to highest:
356         // - float default placement
357         // - document wide default placement
358         // - specific float placement
359         string tmpplacement;
360         string const buf_placement = buffer().params().float_placement;
361         string const def_placement = floats.defaultPlacement(params_.type);
362         if (!params_.placement.empty()
363             && params_.placement != def_placement) {
364                 tmpplacement = params_.placement;
365         } else if (params_.placement.empty()
366                    && !buf_placement.empty()
367                    && buf_placement != def_placement) {
368                 tmpplacement = buf_placement;
369         }
370
371         // Check if placement is allowed by this float
372         string const allowed_placement =
373                 floats.allowedPlacement(params_.type);
374         string placement;
375         string::const_iterator lit = tmpplacement.begin();
376         string::const_iterator end = tmpplacement.end();
377         for (; lit != end; ++lit) {
378                 if (contains(allowed_placement, *lit))
379                         placement += *lit;
380         }
381
382         // Force \begin{<floatname>} to appear in a new line.
383         os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
384         if (runparams.lastid != -1)
385                 os.texrow().start(runparams.lastid, runparams.lastpos);
386         // We only output placement if different from the def_placement.
387         // sidewaysfloats always use their own page
388         if (!placement.empty() && !params_.sideways)
389                 os << '[' << from_ascii(placement) << ']';
390         os << '\n';
391
392         InsetText::latex(os, runparams);
393
394         // Force \end{<floatname>} to appear in a new line.
395         os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
396 }
397
398
399 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
400 {
401         os << '[' << buffer().B_("float") << ' '
402                 << floatName(params_.type) << ":\n";
403         InsetText::plaintext(os, runparams, max_length);
404         os << "\n]";
405
406         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
407 }
408
409
410 int InsetFloat::docbook(odocstream & os, OutputParams const & runparams) const
411 {
412         // FIXME Implement subfloat!
413         // FIXME UNICODE
414         os << '<' << from_ascii(params_.type) << '>';
415         int const i = InsetText::docbook(os, runparams);
416         os << "</" << from_ascii(params_.type) << '>';
417
418         return i;
419 }
420
421
422 bool InsetFloat::insetAllowed(InsetCode code) const
423 {
424         // The case that code == FLOAT_CODE is handled in Text3.cpp, 
425         // because we need to know what type of float is meant.
426         switch(code) {
427         case WRAP_CODE:
428         case FOOT_CODE:
429         case MARGIN_CODE:
430                 return false;
431         default:
432                 return InsetCaptionable::insetAllowed(code);
433         }
434 }
435
436
437 void InsetFloat::setWide(bool w, bool update_label)
438 {
439         if (!buffer().params().documentClass().floats().allowsWide(params_.type))
440                 params_.wide = false;
441         else
442             params_.wide = w;
443         if (update_label)
444                 setNewLabel();
445 }
446
447
448 void InsetFloat::setSideways(bool s, bool update_label)
449 {
450         if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
451                 params_.sideways = false;
452         else
453                 params_.sideways = s;
454         if (update_label)
455                 setNewLabel();
456 }
457
458
459 void InsetFloat::setSubfloat(bool s, bool update_label)
460 {
461         params_.subfloat = s;
462         if (update_label)
463                 setNewLabel();
464 }
465
466
467 void InsetFloat::setNewLabel()
468 {
469         docstring lab = _("float: ");
470
471         if (params_.subfloat)
472                 lab = _("subfloat: ");
473
474         lab += floatName(params_.type);
475
476         FloatList const & floats = buffer().params().documentClass().floats();
477
478         if (params_.wide && floats.allowsWide(params_.type))
479                 lab += '*';
480
481         if (params_.sideways && floats.allowsSideways(params_.type))
482                 lab += _(" (sideways)");
483
484         setLabel(lab);
485 }
486
487
488 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
489 {
490         return !params_.subfloat && newtype != "LongTableNoNumber";
491 }
492
493
494 docstring InsetFloat::getCaption(OutputParams const & runparams) const
495 {
496         TexRow texrow(false);
497         odocstringstream ods;
498         otexstream os(ods, texrow);
499         getCaption(os, runparams);
500         return ods.str();
501 }
502
503
504 void InsetFloat::getCaption(otexstream & os,
505                                                         OutputParams const & runparams) const
506 {
507         if (paragraphs().empty())
508                 return;
509
510         InsetCaption const * ins = getCaptionInset();
511         if (ins == 0)
512                 return;
513
514         ins->getArgs(os, runparams);
515
516         os << '[';
517         TexRow texrow;
518         odocstringstream ods;
519         otexstream oss(ods, texrow);
520         ins->getArgument(oss, runparams);
521         docstring arg = ods.str();
522         // Protect ']'
523         if (arg.find(']') != docstring::npos)
524                 arg = '{' + arg + '}';
525         os.append(arg, texrow);
526         os << ']';
527 }
528
529
530 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
531 {
532         params = InsetFloatParams();
533         if (in.empty())
534                 return;
535
536         istringstream data(in);
537         Lexer lex;
538         lex.setStream(data);
539         lex.setContext("InsetFloat::string2params");
540         params.read(lex);
541 }
542
543
544 string InsetFloat::params2string(InsetFloatParams const & params)
545 {
546         ostringstream data;
547         params.write(data);
548         return data.str();
549 }
550
551
552 } // namespace lyx