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