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