]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
File format change caused by 34eadf5d4.
[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         : InsetCollapsable(buf)
117 {
118         string2params(params_str, params_);
119 }
120
121
122 docstring InsetFloat::layoutName() const
123
124         return "Float:" + from_utf8(params_.type);
125 }
126
127
128 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
129 {
130         if (isOpen(bv))
131                 return InsetCollapsable::toolTip(bv, x, y);
132
133         OutputParams rp(&buffer().params().encoding());
134         return getCaptionText(rp);
135 }
136
137
138 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
139 {
140         switch (cmd.action()) {
141
142         case LFUN_INSET_MODIFY: {
143                 InsetFloatParams params;
144                 string2params(to_utf8(cmd.argument()), params);
145                 cur.recordUndoInset(this);
146
147                 // placement, wide and sideways are not used for subfloats
148                 if (!params_.subfloat) {
149                         params_.placement = params.placement;
150                         params_.wide      = params.wide;
151                         params_.sideways  = params.sideways;
152                 }
153                 setNewLabel();
154                 if (params_.type != params.type) {
155                         params_.type = params.type;
156                         cur.forceBufferUpdate();
157                 }
158                 // what we really want here is a TOC update, but that means
159                 // a full buffer update
160                 cur.forceBufferUpdate();
161                 break;
162         }
163
164         case LFUN_INSET_DIALOG_UPDATE: {
165                 cur.bv().updateDialog("float", params2string(params()));
166                 break;
167         }
168
169         default:
170                 InsetCollapsable::doDispatch(cur, cmd);
171                 break;
172         }
173 }
174
175
176 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
177                 FuncStatus & flag) const
178 {
179         switch (cmd.action()) {
180
181         case LFUN_INSET_MODIFY:
182         case LFUN_INSET_DIALOG_UPDATE:
183                 flag.setEnabled(true);
184                 return true;
185
186         case LFUN_INSET_SETTINGS:
187                 if (InsetCollapsable::getStatus(cur, cmd, flag)) {
188                         flag.setEnabled(flag.enabled() && !params_.subfloat);
189                         return true;
190                 } else
191                         return false;
192         
193         case LFUN_NEWLINE_INSERT:
194                 if (params_.subfloat) {
195                         flag.setEnabled(false);
196                         return true;
197                 }
198
199         default:
200                 return InsetCollapsable::getStatus(cur, cmd, flag);
201         }
202 }
203
204
205 void InsetFloat::updateBuffer(ParIterator const & it, UpdateType utype)
206 {
207         Counters & cnts =
208                 buffer().masterBuffer()->params().documentClass().counters();
209         if (utype == OutputUpdate) {
210                 // counters are local to the float
211                 cnts.saveLastCounter();
212         }
213         string const saveflt = cnts.current_float();
214         bool const savesubflt = cnts.isSubfloat();
215
216         bool const subflt = (it.innerInsetOfType(FLOAT_CODE)
217                              || it.innerInsetOfType(WRAP_CODE));
218         // floats can only embed subfloats of their own kind
219         if (subflt)
220                 params_.type = saveflt;
221         setSubfloat(subflt);
222
223         // Tell to captions what the current float is
224         cnts.current_float(params().type);
225         cnts.isSubfloat(subflt);
226
227         InsetCollapsable::updateBuffer(it, utype);
228
229         //reset afterwards
230         cnts.current_float(saveflt);
231         if (utype == OutputUpdate)
232                 cnts.restoreLastCounter();
233         cnts.isSubfloat(savesubflt);
234 }
235
236
237 void InsetFloatParams::write(ostream & os) const
238 {
239         os << type << '\n';
240
241         if (!placement.empty())
242                 os << "placement " << placement << "\n";
243
244         if (wide)
245                 os << "wide true\n";
246         else
247                 os << "wide false\n";
248
249         if (sideways)
250                 os << "sideways true\n";
251         else
252                 os << "sideways false\n";
253 }
254
255
256 void InsetFloatParams::read(Lexer & lex)
257 {
258         lex.setContext("InsetFloatParams::read");
259         lex >> type;
260         if (lex.checkFor("placement"))
261                 lex >> placement;
262         lex >> "wide" >> wide;
263         lex >> "sideways" >> sideways;
264 }
265
266
267 void InsetFloat::write(ostream & os) const
268 {
269         os << "Float ";
270         params_.write(os);
271         InsetCollapsable::write(os);
272 }
273
274
275 void InsetFloat::read(Lexer & lex)
276 {
277         params_.read(lex);
278         InsetCollapsable::read(lex);
279         // check if the float type exists
280         if (buffer().params().documentClass().floats().typeExist(params_.type))
281                 setLabel(_("float: ") + floatName(params_.type));
282         else
283                 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
284 }
285
286
287 void InsetFloat::validate(LaTeXFeatures & features) const
288 {
289         if (support::contains(params_.placement, 'H'))
290                 features.require("float");
291
292         if (params_.sideways)
293                 features.require("rotfloat");
294
295         if (features.inFloat())
296                 features.require("subfig");
297
298         features.useFloat(params_.type, features.inFloat());
299         features.inFloat(true);
300         InsetCollapsable::validate(features);
301         features.inFloat(false);
302 }
303
304
305 docstring InsetFloat::xhtml(XHTMLStream & xs, OutputParams const & rp) const
306 {
307         FloatList const & floats = buffer().params().documentClass().floats();
308         Floating const & ftype = floats.getType(params_.type);
309         string const & htmltype = ftype.htmlTag();
310         string const & attr = ftype.htmlAttrib();
311
312         odocstringstream ods;
313         XHTMLStream newxs(ods);
314         newxs << html::StartTag(htmltype, attr);
315         InsetText::XHTMLOptions const opts = 
316                 InsetText::WriteLabel | InsetText::WriteInnerTag;
317         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
318         newxs << html::EndTag(htmltype);
319
320         if (rp.inFloat == OutputParams::NONFLOAT)
321                 // In this case, this float needs to be deferred, but we'll put it
322                 // before anything the text itself deferred.
323                 deferred = ods.str() + '\n' + deferred;
324         else 
325                 // In this case, the whole thing is already being deferred, so
326                 // we can write to the stream.
327                 // Note that things will already have been escaped, so we do not 
328                 // want to escape them again.
329                 xs << XHTMLStream::ESCAPE_NONE << ods.str();
330         return deferred;
331 }
332
333
334 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
335 {
336         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
337                 if (runparams_in.moving_arg)
338                         os << "\\protect";
339                 os << "\\subfloat";
340
341                 OutputParams rp = runparams_in;
342                 rp.moving_arg = true;
343                 docstring const caption = getCaption(rp);
344                 if (!caption.empty()) {
345                         os << caption;
346                 }
347                 os << '{';
348                 // The main argument is the contents of the float. This is not a moving argument.
349                 rp.moving_arg = false;
350                 rp.inFloat = OutputParams::SUBFLOAT;
351                 InsetText::latex(os, rp);
352                 os << "}";
353
354                 return;
355         }
356         OutputParams runparams(runparams_in);
357         runparams.inFloat = OutputParams::MAINFLOAT;
358
359         FloatList const & floats = buffer().params().documentClass().floats();
360         string tmptype = params_.type;
361         if (params_.sideways)
362                 tmptype = "sideways" + params_.type;
363         if (params_.wide && (!params_.sideways ||
364                              params_.type == "figure" ||
365                              params_.type == "table"))
366                 tmptype += "*";
367         // Figure out the float placement to use.
368         // From lowest to highest:
369         // - float default placement
370         // - document wide default placement
371         // - specific float placement
372         string placement;
373         string const buf_placement = buffer().params().float_placement;
374         string const def_placement = floats.defaultPlacement(params_.type);
375         if (!params_.placement.empty()
376             && params_.placement != def_placement) {
377                 placement = params_.placement;
378         } else if (params_.placement.empty()
379                    && !buf_placement.empty()
380                    && buf_placement != def_placement) {
381                 placement = buf_placement;
382         }
383
384         // Force \begin{<floatname>} to appear in a new line.
385         os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
386         if (runparams.lastid != -1)
387                 os.texrow().start(runparams.lastid, runparams.lastpos);
388         // We only output placement if different from the def_placement.
389         // sidewaysfloats always use their own page
390         if (!placement.empty() && !params_.sideways)
391                 os << '[' << from_ascii(placement) << ']';
392         os << '\n';
393
394         InsetText::latex(os, runparams);
395
396         // Force \end{<floatname>} to appear in a new line.
397         os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
398 }
399
400
401 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
402 {
403         os << '[' << buffer().B_("float") << ' '
404                 << floatName(params_.type) << ":\n";
405         InsetText::plaintext(os, runparams, max_length);
406         os << "\n]";
407
408         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
409 }
410
411
412 int InsetFloat::docbook(odocstream & os, OutputParams const & runparams) const
413 {
414         // FIXME Implement subfloat!
415         // FIXME UNICODE
416         os << '<' << from_ascii(params_.type) << '>';
417         int const i = InsetText::docbook(os, runparams);
418         os << "</" << from_ascii(params_.type) << '>';
419
420         return i;
421 }
422
423
424 bool InsetFloat::insetAllowed(InsetCode code) const
425 {
426         // The case that code == FLOAT_CODE is handled in Text3.cpp, 
427         // because we need to know what type of float is meant.
428         switch(code) {
429         case WRAP_CODE:
430         case FOOT_CODE:
431         case MARGIN_CODE:
432                 return false;
433         default:
434                 return InsetCollapsable::insetAllowed(code);
435         }
436 }
437
438
439 void InsetFloat::setWide(bool w, bool update_label)
440 {
441         params_.wide = w;
442         if (update_label)
443                 setNewLabel();
444 }
445
446
447 void InsetFloat::setSideways(bool s, bool update_label)
448 {
449         params_.sideways = s;
450         if (update_label)
451                 setNewLabel();
452 }
453
454
455 void InsetFloat::setSubfloat(bool s, bool update_label)
456 {
457         params_.subfloat = s;
458         if (update_label)
459                 setNewLabel();
460 }
461
462
463 void InsetFloat::setNewLabel()
464 {
465         docstring lab = _("float: ");
466
467         if (params_.subfloat)
468                 lab = _("subfloat: ");
469
470         lab += floatName(params_.type);
471
472         if (params_.wide)
473                 lab += '*';
474
475         if (params_.sideways)
476                 lab += _(" (sideways)");
477
478         setLabel(lab);
479 }
480
481
482 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
483 {
484         return !params_.subfloat && newtype != "LongTableNoNumber";
485 }
486
487
488 docstring InsetFloat::getCaption(OutputParams const & runparams) const
489 {
490         if (paragraphs().empty())
491                 return docstring();
492
493         InsetCaption const * ins = getCaptionInset();
494         if (ins == 0)
495                 return docstring();
496
497         TexRow texrow;
498         odocstringstream ods;
499         otexstream os(ods, texrow);
500         ins->getArgs(os, runparams);
501         ods << '[';
502         odocstringstream odss;
503         otexstream oss(odss, texrow);
504         ins->getArgument(oss, runparams);
505         docstring arg = odss.str();
506         // Protect ']'
507         if (arg.find(']') != docstring::npos)
508                 arg = '{' + arg + '}';
509         ods << arg;
510         ods << ']';
511         return ods.str();
512 }
513
514
515 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
516 {
517         params = InsetFloatParams();
518         if (in.empty())
519                 return;
520
521         istringstream data(in);
522         Lexer lex;
523         lex.setStream(data);
524         lex.setContext("InsetFloat::string2params");
525         params.read(lex);
526 }
527
528
529 string InsetFloat::params2string(InsetFloatParams const & params)
530 {
531         ostringstream data;
532         params.write(data);
533         return data.str();
534 }
535
536
537 } // namespace lyx