2 * \file InsetCaption.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "InsetCaption.h"
14 #include "InsetFloat.h"
15 #include "InsetWrap.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
21 #include "Dimension.h"
23 #include "FloatList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "InsetList.h"
29 #include "MetricsInfo.h"
31 #include "output_latex.h"
32 #include "output_xhtml.h"
33 #include "Paragraph.h"
34 #include "ParIterator.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TextMetrics.h"
39 #include "TocBackend.h"
41 #include "frontends/FontMetrics.h"
42 #include "frontends/Painter.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
50 using namespace lyx::support;
55 InsetCaption::InsetCaption(Buffer * buf, string const & type)
56 : InsetText(buf, InsetText::PlainLayout), type_(type)
59 setFrameColor(Color_collapsibleframe);
63 void InsetCaption::write(ostream & os) const
73 docstring InsetCaption::layoutName() const
76 return from_ascii("Caption");
77 return from_utf8("Caption:" + type_);
81 void InsetCaption::cursorPos(BufferView const & bv,
82 CursorSlice const & sl, bool boundary, int & x, int & y) const
84 InsetText::cursorPos(bv, sl, boundary, x, y);
90 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active,
91 UpdateType utype, TocBackend & backend) const
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
104 text().forOutliner(str, length);
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);
112 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
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_;
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;
129 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
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();
135 x+= + dimension(*pi.base.bv).wid - labelwidth_;
136 pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
140 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
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)
148 // Answer: the text inset (in buffer_funcs.cpp: setCaption).
151 FontInfo tmpfont = pi.base.font;
152 pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
154 pi.base.font.setStrikeout(FONT_ON);
155 else if (isChanged() && lyxrc.ct_additions_underlined)
156 pi.base.font.setUnderbar(FONT_ON);
157 int const lo = leftOffset(pi.base.bv);
159 InsetText::draw(pi, x, y);
160 pi.pain.text(x + dimension(*pi.base.bv).wid - labelwidth_ + lo,
161 y, full_label_, pi.base.font);
163 pi.pain.text(x + lo, y, full_label_, pi.base.font);
164 InsetText::draw(pi, x + labelwidth_, y);
166 pi.base.font = tmpfont;
170 void InsetCaption::edit(Cursor & cur, bool front, EntryDirection entry_from)
173 InsetText::edit(cur, front, entry_from);
177 Inset * InsetCaption::editXY(Cursor & cur, int x, int y)
180 return InsetText::editXY(cur, x, y);
184 bool InsetCaption::insetAllowed(InsetCode code) const
187 // code that is not allowed in a caption
198 return InsetText::insetAllowed(code);
203 void InsetCaption::doDispatch(Cursor & cur, FuncRequest & cmd)
205 switch (cmd.action()) {
207 case LFUN_INSET_MODIFY: {
208 if (cmd.getArg(0) == "changetype") {
209 cur.recordUndoInset(this);
210 type_ = cmd.getArg(1);
211 cur.forceBufferUpdate();
219 InsetText::doDispatch(cur, cmd);
225 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
226 FuncStatus & status) const
228 switch (cmd.action()) {
230 case LFUN_INSET_MODIFY: {
231 string const first_arg = cmd.getArg(0);
232 if (first_arg == "changetype") {
233 string const type = cmd.getArg(1);
234 status.setOnOff(type == type_);
235 bool varia = type != "Unnumbered";
236 // check if the immediate parent inset allows caption variation
237 if (cur.depth() > 1) {
238 varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
240 status.setEnabled(!is_subfloat_ && varia
241 && buffer().params().documentClass().hasInsetLayout(
242 from_ascii("Caption:" + type)));
245 return InsetText::getStatus(cur, cmd, status);
248 case LFUN_INSET_TOGGLE:
249 // pass back to owner
254 return InsetText::getStatus(cur, cmd, status);
259 void InsetCaption::latex(otexstream & os,
260 OutputParams const & runparams_in) const
262 if (runparams_in.inFloat == OutputParams::SUBFLOAT)
263 // caption is output as an optional argument
265 // This is a bit too simplistic to take advantage of
266 // caption options we must add more later. (Lgb)
267 // This code is currently only able to handle the simple
268 // \caption{...}, later we will make it take advantage
269 // of the one of the caption packages. (Lgb)
270 OutputParams runparams = runparams_in;
271 // Some fragile commands (labels, index entries)
272 // are output after the caption (#2154)
273 runparams.postpone_fragile_stuff = buffer().masterParams().postpone_fragile_content;
274 InsetText::latex(os, runparams);
275 if (!runparams.post_macro.empty()) {
276 // Output the stored fragile commands (labels, indices etc.)
277 // that need to be output after the caption.
278 os << runparams.post_macro;
279 runparams.post_macro.clear();
281 // Backwards compatibility: We always had a linebreak after
282 // the caption (see #8514)
284 runparams_in.encoding = runparams.encoding;
288 int InsetCaption::plaintext(odocstringstream & os,
289 OutputParams const & runparams, size_t max_length) const
291 os << '[' << full_label_ << "\n";
292 InsetText::plaintext(os, runparams, max_length);
295 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
299 void InsetCaption::docbook(XMLStream &, OutputParams const &) const
301 // This function should never be called (rather InsetFloat::docbook, the titles should be skipped in floats).
305 docstring InsetCaption::xhtml(XMLStream & xs, OutputParams const & rp) const
307 if (rp.html_disable_captions)
309 InsetLayout const & il = getLayout();
310 string const & tag = il.htmltag();
311 string attr = il.htmlattr();
312 if (!type_.empty()) {
313 string const our_class = "float-caption-" + type_;
314 size_t const loc = attr.find("class='");
315 if (loc != string::npos)
316 attr.insert(loc + 7, our_class + " ");
318 attr = attr + " class='" + our_class + "'";
320 xs << xml::StartTag(tag, attr);
321 docstring def = getCaptionAsHTML(xs, rp);
322 xs << xml::EndTag(tag);
327 void InsetCaption::getArgument(otexstream & os,
328 OutputParams const & runparams) const
330 InsetLayout const & il = getLayout();
332 if (!il.leftdelim().empty())
333 os << il.leftdelim();
335 OutputParams rp = runparams;
338 if (il.isNeedProtect())
339 rp.moving_arg = true;
340 if (il.isNeedMBoxProtect())
343 rp.par_end = paragraphs().size();
345 // Output the contents of the inset
346 if (!paragraphs().empty())
347 os.texrow().forceStart(paragraphs()[0].id(), 0);
348 latexParagraphs(buffer(), text(), os, rp);
349 runparams.encoding = rp.encoding;
351 if (!il.rightdelim().empty())
352 os << il.rightdelim();
356 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
357 OutputParams const & runparams) const
359 os << full_label_ << ' ';
360 odocstringstream ods;
361 int const retval = InsetText::plaintext(ods, runparams);
367 void InsetCaption::getCaptionAsDocBook(XMLStream & xs,
368 OutputParams const & runparams) const
370 if (runparams.docbook_in_float)
373 // Ignore full_label_, as the DocBook processor will deal with the numbering.
374 InsetText::XHTMLOptions opts = InsetText::WriteInnerTag;
375 InsetText::docbook(xs, runparams, opts);
379 docstring InsetCaption::getCaptionAsHTML(XMLStream & xs,
380 OutputParams const & runparams) const
382 xs << full_label_ << ' ';
383 InsetText::XHTMLOptions const opts =
384 InsetText::WriteLabel | InsetText::WriteInnerTag;
385 return InsetText::insetAsXHTML(xs, runparams, opts);
389 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
391 Buffer const & master = *buffer().masterBuffer();
392 DocumentClass const & tclass = master.params().documentClass();
393 string const & lang = it.paragraph().getParLanguage(master.params())->code();
394 Counters & cnts = tclass.counters();
395 string const & type = cnts.current_float();
396 if (utype == OutputUpdate) {
397 // counters are local to the caption
398 cnts.saveLastCounter();
400 is_deleted_ = deleted;
401 // Memorize type for addToToc().
403 if (type.empty() || type == "senseless")
404 full_label_ = master.B_("Senseless!!! ");
406 // FIXME: life would be _much_ simpler if listings was
407 // listed in Floating.
409 if (type == "listing")
410 name = master.B_("Listing");
412 name = master.B_(tclass.floats().getType(type).name());
413 docstring counter = from_utf8(type);
414 is_subfloat_ = cnts.isSubfloat();
416 // only standard captions allowed in subfloats
418 counter = "sub-" + from_utf8(type);
419 name = bformat(_("Sub-%1$s"),
420 master.B_(tclass.floats().getType(type).name()));
423 docstring const lstring = getLayout().labelstring();
424 docstring const labelstring = isAscii(lstring) ?
425 master.B_(to_ascii(lstring)) : lstring;
426 if (cnts.hasCounter(counter)) {
427 int val = cnts.value(counter);
428 // for longtables, we step the counter upstream
429 if (!cnts.isLongtable())
430 cnts.step(counter, utype);
431 sec = cnts.theCounter(counter, lang);
432 if (deleted && !cnts.isLongtable())
433 // un-step after deleted counter
434 cnts.set(counter, val);
436 if (labelstring != master.B_("standard")) {
438 sec += from_ascii(" ");
439 sec += bformat(from_ascii("(%1$s)"), labelstring);
442 sec = from_ascii("#");
443 full_label_ = bformat(master.B_("%1$s %2$s: [[Caption label (ex. Figure 1: )]]"), name, sec);
446 // Do the real work now.
447 InsetText::updateBuffer(it, utype, deleted);
448 if (utype == OutputUpdate)
449 cnts.restoreLastCounter();
453 string InsetCaption::contextMenuName() const
455 return "context-caption";