]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Remove indentation on screen after a plain separator inset
[lyx.git] / src / insets / InsetCaption.cpp
1 /**
2  * \file InsetCaption.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetCaption.h"
14 #include "InsetFloat.h"
15 #include "InsetWrap.h"
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "Cursor.h"
21 #include "Dimension.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "InsetList.h"
27 #include "Language.h"
28 #include "LyXRC.h"
29 #include "MetricsInfo.h"
30 #include "xml.h"
31 #include "output_latex.h"
32 #include "output_xhtml.h"
33 #include "Paragraph.h"
34 #include "ParIterator.h"
35 #include "TexRow.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TextMetrics.h"
39 #include "TocBackend.h"
40
41 #include "frontends/FontMetrics.h"
42 #include "frontends/Painter.h"
43
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46
47 #include <sstream>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54
55 InsetCaption::InsetCaption(Buffer * buf, string const & type)
56     : InsetText(buf, InsetText::PlainLayout), type_(type)
57 {
58         setDrawFrame(true);
59         setFrameColor(Color_collapsibleframe);
60 }
61
62
63 void InsetCaption::write(ostream & os) const
64 {
65         os << "Caption";
66         if (!type_.empty())
67                 os << ' ' << type_;
68         os << '\n';
69         text().write(os);
70 }
71
72
73 docstring InsetCaption::layoutName() const
74 {
75         if (type_.empty())
76                 return from_ascii("Caption");
77         return from_utf8("Caption:" + type_);
78 }
79
80
81 void InsetCaption::cursorPos(BufferView const & bv,
82                 CursorSlice const & sl, bool boundary, int & x, int & y) const
83 {
84         InsetText::cursorPos(bv, sl, boundary, x, y);
85         if (!rtl_)
86                 x += labelwidth_;
87 }
88
89
90 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active,
91                                                         UpdateType utype, TocBackend & backend) const
92 {
93         string const & type = floattype_.empty() ? "senseless" : floattype_;
94         DocIterator pit = cpit;
95         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
96         int length = (utype == OutputUpdate) ?
97                 // For output (e.g. xhtml) all (bug #8603) or nothing
98                 (output_active ? INT_MAX : 0) :
99                 // TOC for LyX interface
100                 TOC_ENTRY_LENGTH;
101         docstring str;
102         if (length > 0) {
103                 str = full_label_;
104                 text().forOutliner(str, length);
105         }
106         backend.builder(type).captionItem(pit, str, output_active);
107         // Proceed with the rest of the inset.
108         InsetText::addToToc(cpit, output_active, utype, backend);
109 }
110
111
112 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
113 {
114         labelwidth_ = theFontMetrics(mi.base.font).width(full_label_);
115         // add some space to separate the label from the inset text
116         labelwidth_ += leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
117         dim.wid = labelwidth_;
118         Dimension textdim;
119         // Correct for button and label width
120         mi.base.textwidth -= dim.wid;
121         InsetText::metrics(mi, textdim);
122         mi.base.textwidth += dim.wid;
123         dim.des = max(dim.des - textdim.asc + dim.asc, textdim.des);
124         dim.asc = textdim.asc;
125         dim.wid += textdim.wid;
126 }
127
128
129 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
130 {
131         TextMetrics & tm = pi.base.bv->textMetrics(&text());
132         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
133         int const yy = y - topOffset(pi.base.bv) - tm.ascent();
134         if (rtl_)
135                 x+= + dimension(*pi.base.bv).wid - labelwidth_;
136         pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
137 }
138
139
140 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
141 {
142         // We must draw the label, we should get the label string
143         // from the enclosing float inset.
144         // The question is: Who should draw the label, the caption inset,
145         // the text inset or the paragraph?
146         // We should also draw the float number (Lgb)
147
148         // Answer: the text inset (in buffer_funcs.cpp: setCaption).
149
150         rtl_ = !pi.ltr_pos;
151         FontInfo tmpfont = pi.base.font;
152         if (non_float_)
153                 pi.base.font.setColor(Color_error);
154         else
155                 pi.base.font.setPaintColor(pi.textColor(pi.base.font.color()));
156         int const lo = leftOffset(pi.base.bv);
157         if (rtl_) {
158                 InsetText::draw(pi, x, y);
159                 pi.pain.text(x + dimension(*pi.base.bv).wid - labelwidth_ + lo,
160                              y, full_label_, pi.base.font);
161         } else {
162                 pi.pain.text(x + lo, y, full_label_, pi.base.font);
163                 InsetText::draw(pi, x + labelwidth_, y);
164         }
165         // Draw the change tracking cue on the label, unless RowPainter already
166         // takes care of it.
167         if (canPaintChange(*pi.base.bv))
168                 pi.change.paintCue(pi, x, y, x + labelwidth_, pi.base.font);
169         pi.base.font = tmpfont;
170 }
171
172
173 void InsetCaption::edit(Cursor & cur, bool front, EntryDirection entry_from)
174 {
175         cur.push(*this);
176         InsetText::edit(cur, front, entry_from);
177 }
178
179
180 Inset * InsetCaption::editXY(Cursor & cur, int x, int y)
181 {
182         cur.push(*this);
183         return InsetText::editXY(cur, x, y);
184 }
185
186
187 bool InsetCaption::insetAllowed(InsetCode code) const
188 {
189         switch (code) {
190         // code that is not allowed in a caption
191         case CAPTION_CODE:
192         case FLOAT_CODE:
193         case FOOT_CODE:
194         case NEWPAGE_CODE:
195         case MARGIN_CODE:
196         case MATHMACRO_CODE:
197         case TABULAR_CODE:
198         case WRAP_CODE:
199                 return false;
200         default:
201                 return InsetText::insetAllowed(code);
202         }
203 }
204
205
206 void InsetCaption::doDispatch(Cursor & cur, FuncRequest & cmd)
207 {
208         switch (cmd.action()) {
209
210         case LFUN_INSET_MODIFY: {
211                 if (cmd.getArg(0) == "changetype") {
212                         cur.recordUndoInset(this);
213                         type_ = cmd.getArg(1);
214                         cur.forceBufferUpdate();
215                         break;
216                 }
217         }
218         // no "changetype":
219         // fall through
220
221         default:
222                 InsetText::doDispatch(cur, cmd);
223                 break;
224         }
225 }
226
227
228 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
229         FuncStatus & status) const
230 {
231         switch (cmd.action()) {
232
233         case LFUN_INSET_MODIFY: {
234                 string const first_arg = cmd.getArg(0);
235                 if (first_arg == "changetype") {
236                         string const type = cmd.getArg(1);
237                         status.setOnOff(type == type_);
238                         bool varia = type != "Unnumbered";
239                         // check if the immediate parent inset allows caption variation
240                         if (cur.depth() > 1) {
241                                 varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
242                         }
243                         status.setEnabled(!is_subfloat_ && varia
244                                           && buffer().params().documentClass().hasInsetLayout(
245                                                 from_ascii("Caption:" + type)));
246                         return true;
247                 }
248                 return InsetText::getStatus(cur, cmd, status);
249         }
250
251         case LFUN_INSET_TOGGLE:
252                 // pass back to owner
253                 cur.undispatched();
254                 return false;
255
256         default:
257                 return InsetText::getStatus(cur, cmd, status);
258         }
259 }
260
261
262 void InsetCaption::latex(otexstream & os,
263                          OutputParams const & runparams_in) const
264 {
265         if (runparams_in.inFloat == OutputParams::SUBFLOAT)
266                 // caption is output as an optional argument
267                 return;
268         // This is a bit too simplistic to take advantage of
269         // caption options we must add more later. (Lgb)
270         // This code is currently only able to handle the simple
271         // \caption{...}, later we will make it take advantage
272         // of the one of the caption packages. (Lgb)
273         OutputParams runparams = runparams_in;
274         // Some fragile commands (labels, index entries)
275         // are output after the caption (#2154)
276         runparams.postpone_fragile_stuff = buffer().masterParams().postpone_fragile_content;
277         InsetText::latex(os, runparams);
278         if (!runparams.post_macro.empty()) {
279                 // Output the stored fragile commands (labels, indices etc.)
280                 // that need to be output after the caption.
281                 os << runparams.post_macro;
282                 runparams.post_macro.clear();
283         }
284         // Backwards compatibility: We always had a linebreak after
285         // the caption (see #8514)
286         os << breakln;
287         runparams_in.encoding = runparams.encoding;
288 }
289
290
291 int InsetCaption::plaintext(odocstringstream & os,
292                             OutputParams const & runparams, size_t max_length) const
293 {
294         os << '[' << full_label_ << "\n";
295         InsetText::plaintext(os, runparams, max_length);
296         os << "\n]";
297
298         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
299 }
300
301
302 void InsetCaption::docbook(XMLStream &, OutputParams const &) const
303 {
304         // This function should never be called (rather InsetFloat::docbook, the titles should be skipped in floats).
305 }
306
307
308 docstring InsetCaption::xhtml(XMLStream & xs, OutputParams const & rp) const
309 {
310         if (rp.html_disable_captions)
311                 return docstring();
312         InsetLayout const & il = getLayout();
313         string const & tag = il.htmltag();
314         string attr = il.htmlGetAttrString();
315         if (!type_.empty()) {
316                 string const our_class = "float-caption-" + type_;
317                 size_t const loc = attr.find("class='");
318                 if (loc != string::npos)
319                         attr.insert(loc + 7, our_class + " ");
320                 else
321                         attr = attr + " class='" + our_class + "'";
322         }
323         xs << xml::StartTag(tag, attr);
324         docstring def = getCaptionAsHTML(xs, rp);
325         xs << xml::EndTag(tag);
326         return def;
327 }
328
329
330 docstring InsetCaption::toolTip(BufferView const & bv, int x, int y) const
331 {
332         if (non_float_)
333                 return _("Standard captions are not allowed outside floats. You will get a LaTeX error.\n"
334                          "For captions outside floats, you can use the 'nonfloat' LaTeX package.");
335         return InsetText::toolTip(bv, x, y);
336 }
337
338
339 void InsetCaption::getArgument(otexstream & os,
340                         OutputParams const & runparams) const
341 {
342         InsetLayout const & il = getLayout();
343
344         if (!il.leftdelim().empty())
345                 os << il.leftdelim();
346
347         OutputParams rp = runparams;
348         if (isPassThru())
349                 rp.pass_thru = true;
350         if (il.isNeedProtect())
351                 rp.moving_arg = true;
352         if (il.isNeedMBoxProtect())
353                 ++rp.inulemcmd;
354         rp.par_begin = 0;
355         rp.par_end = paragraphs().size();
356
357         // Output the contents of the inset
358         if (!paragraphs().empty())
359                 os.texrow().forceStart(paragraphs()[0].id(), 0);
360         latexParagraphs(buffer(), text(), os, rp);
361         runparams.encoding = rp.encoding;
362
363         if (!il.rightdelim().empty())
364                 os << il.rightdelim();
365 }
366
367
368 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
369                         OutputParams const & runparams) const
370 {
371         os << full_label_ << ' ';
372         odocstringstream ods;
373         int const retval = InsetText::plaintext(ods, runparams);
374         os << ods.str();
375         return retval;
376 }
377
378
379 void InsetCaption::getCaptionAsDocBook(XMLStream & xs,
380                                        OutputParams const & runparams) const
381 {
382         if (runparams.docbook_in_float)
383                 return;
384
385         // Ignore full_label_, as the DocBook processor will deal with the numbering.
386         InsetText::XHTMLOptions opts = InsetText::WriteInnerTag;
387         InsetText::docbook(xs, runparams, opts);
388 }
389
390
391 docstring InsetCaption::getCaptionAsHTML(XMLStream & xs,
392                         OutputParams const & runparams) const
393 {
394         xs << full_label_ << ' ';
395         InsetText::XHTMLOptions const opts =
396                 InsetText::WriteLabel | InsetText::WriteInnerTag;
397         return InsetText::insetAsXHTML(xs, runparams, opts);
398 }
399
400
401 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
402 {
403         Buffer const & master = *buffer().masterBuffer();
404         DocumentClass const & tclass = master.params().documentClass();
405         string const & lang = it.paragraph().getParLanguage(master.params())->code();
406         Counters & cnts = tclass.counters();
407         string const & type = cnts.current_float();
408         if (utype == OutputUpdate) {
409                 // counters are local to the caption
410                 cnts.saveLastCounter();
411         }
412         is_deleted_ = deleted;
413         // Memorize type for addToToc().
414         floattype_ = type;
415         if (type.empty() || type == "senseless") {
416                 full_label_ = master.B_("Orphaned caption:");
417                 non_float_ = true;
418         } else {
419                 // FIXME: life would be _much_ simpler if listings was
420                 // listed in Floating.
421                 docstring name;
422                 if (type == "listing")
423                         name = master.B_("Listing");
424                 else
425                         name = master.B_(tclass.floats().getType(type).name());
426                 docstring counter = from_utf8(type);
427                 is_subfloat_ = cnts.isSubfloat();
428                 if (is_subfloat_) {
429                         // only standard captions allowed in subfloats
430                         type_ = "Standard";
431                         counter = "sub-" + from_utf8(type);
432                         name = bformat(_("Sub-%1$s"),
433                                        master.B_(tclass.floats().getType(type).name()));
434                 }
435                 docstring sec;
436                 docstring const lstring = getLayout().labelstring();
437                 docstring const labelstring = isAscii(lstring) ?
438                                 master.B_(to_ascii(lstring)) : lstring;
439                 if (cnts.hasCounter(counter)) {
440                         int val = cnts.value(counter);
441                         // for longtables, we step the counter upstream
442                         if (!cnts.isLongtable())
443                                 cnts.step(counter, utype);
444                         sec = cnts.theCounter(counter, lang);
445                         if (deleted && !cnts.isLongtable())
446                                 // un-step after deleted counter
447                                 cnts.set(counter, val);
448                 }
449                 if (labelstring != master.B_("standard")) {
450                         if (!sec.empty())
451                                 sec += from_ascii(" ");
452                         sec += bformat(from_ascii("(%1$s)"), labelstring);
453                 }
454                 if (sec.empty())
455                         sec = from_ascii("#");
456                 full_label_ = bformat(master.B_("%1$s %2$s: [[Caption label (ex. Figure 1: )]]"), name, sec);
457                 non_float_ = false;
458         }
459
460         // Do the real work now.
461         InsetText::updateBuffer(it, utype, deleted);
462         if (utype == OutputUpdate)
463                 cnts.restoreLastCounter();
464 }
465
466
467 string InsetCaption::contextMenuName() const
468 {
469         return "context-caption";
470 }
471
472
473 } // namespace lyx