]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Tell updateBuffer whether an inset is deleted.
[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 "MetricsInfo.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
34 #include "TexRow.h"
35 #include "texstream.h"
36 #include "TextClass.h"
37 #include "TextMetrics.h"
38 #include "TocBackend.h"
39
40 #include "frontends/FontMetrics.h"
41 #include "frontends/Painter.h"
42
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45
46 #include <sstream>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53
54 InsetCaption::InsetCaption(Buffer * buf, string const & type)
55     : InsetText(buf, InsetText::PlainLayout),
56       labelwidth_(0), is_subfloat_(false), 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         x += labelwidth_;
86 }
87
88
89 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active,
90                                                         UpdateType utype, TocBackend & backend) const
91 {
92         string const & type = floattype_.empty() ? "senseless" : floattype_;
93         DocIterator pit = cpit;
94         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
95         int length = (utype == OutputUpdate) ?
96                 // For output (e.g. xhtml) all (bug #8603) or nothing
97                 (output_active ? INT_MAX : 0) :
98                 // TOC for LyX interface
99                 TOC_ENTRY_LENGTH;
100         docstring str;
101         if (length > 0) {
102                 str = full_label_;
103                 text().forOutliner(str, length);
104         }
105         backend.builder(type).captionItem(pit, str, output_active);
106         // Proceed with the rest of the inset.
107         InsetText::addToToc(cpit, output_active, utype, backend);
108 }
109
110
111 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
112 {
113         FontInfo tmpfont = mi.base.font;
114         mi.base.font = mi.base.bv->buffer().params().getFont().fontInfo();
115         labelwidth_ = theFontMetrics(mi.base.font).width(full_label_);
116         // add some space to separate the label from the inset text
117         labelwidth_ += leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
118         dim.wid = labelwidth_;
119         Dimension textdim;
120         // Correct for button and label width
121         mi.base.textwidth -= dim.wid;
122         InsetText::metrics(mi, textdim);
123         mi.base.font = tmpfont;
124         mi.base.textwidth += dim.wid;
125         dim.des = max(dim.des - textdim.asc + dim.asc, textdim.des);
126         dim.asc = textdim.asc;
127         dim.wid += textdim.wid;
128 }
129
130
131 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
132 {
133         TextMetrics & tm = pi.base.bv->textMetrics(&text());
134         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
135         int const yy = y - topOffset(pi.base.bv) - tm.ascent();
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         FontInfo tmpfont = pi.base.font;
151         pi.base.font = pi.base.bv->buffer().params().getFont().fontInfo();
152         pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
153         int const xx = x + leftOffset(pi.base.bv);
154         pi.pain.text(xx, y, full_label_, pi.base.font);
155         InsetText::draw(pi, x + labelwidth_, y);
156         pi.base.font = tmpfont;
157 }
158
159
160 void InsetCaption::edit(Cursor & cur, bool front, EntryDirection entry_from)
161 {
162         cur.push(*this);
163         InsetText::edit(cur, front, entry_from);
164 }
165
166
167 Inset * InsetCaption::editXY(Cursor & cur, int x, int y)
168 {
169         cur.push(*this);
170         return InsetText::editXY(cur, x, y);
171 }
172
173
174 bool InsetCaption::insetAllowed(InsetCode code) const
175 {
176         switch (code) {
177         // code that is not allowed in a caption
178         case CAPTION_CODE:
179         case FLOAT_CODE:
180         case FOOT_CODE:
181         case NEWPAGE_CODE:
182         case MARGIN_CODE:
183         case MATHMACRO_CODE:
184         case TABULAR_CODE:
185         case WRAP_CODE:
186                 return false;
187         default:
188                 return InsetText::insetAllowed(code);
189         }
190 }
191
192
193 void InsetCaption::doDispatch(Cursor & cur, FuncRequest & cmd)
194 {
195         switch (cmd.action()) {
196
197         case LFUN_INSET_MODIFY: {
198                 if (cmd.getArg(0) == "changetype") {
199                         cur.recordUndoInset(this);
200                         type_ = cmd.getArg(1);
201                         cur.forceBufferUpdate();
202                         break;
203                 }
204         }
205         // no "changetype":
206         // fall through
207
208         default:
209                 InsetText::doDispatch(cur, cmd);
210                 break;
211         }
212 }
213
214
215 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
216         FuncStatus & status) const
217 {
218         switch (cmd.action()) {
219
220         case LFUN_INSET_MODIFY: {
221                 string const first_arg = cmd.getArg(0);
222                 if (first_arg == "changetype") {
223                         string const type = cmd.getArg(1);
224                         status.setOnOff(type == type_);
225                         bool varia = type != "Unnumbered";
226                         // check if the immediate parent inset allows caption variation
227                         if (cur.depth() > 1) {
228                                 varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
229                         }
230                         status.setEnabled(varia
231                                           && buffer().params().documentClass().hasInsetLayout(
232                                                 from_ascii("Caption:" + type)));
233                         return true;
234                 }
235                 return InsetText::getStatus(cur, cmd, status);
236         }
237
238         case LFUN_INSET_TOGGLE:
239                 // pass back to owner
240                 cur.undispatched();
241                 return false;
242
243         default:
244                 return InsetText::getStatus(cur, cmd, status);
245         }
246 }
247
248
249 void InsetCaption::latex(otexstream & os,
250                          OutputParams const & runparams_in) const
251 {
252         if (runparams_in.inFloat == OutputParams::SUBFLOAT)
253                 // caption is output as an optional argument
254                 return;
255         // This is a bit too simplistic to take advantage of
256         // caption options we must add more later. (Lgb)
257         // This code is currently only able to handle the simple
258         // \caption{...}, later we will make it take advantage
259         // of the one of the caption packages. (Lgb)
260         OutputParams runparams = runparams_in;
261         // Some fragile commands (labels, index entries)
262         // are output after the caption (#2154)
263         runparams.postpone_fragile_stuff = buffer().masterParams().postpone_fragile_content;
264         InsetText::latex(os, runparams);
265         if (!runparams.post_macro.empty()) {
266                 // Output the stored fragile commands (labels, indices etc.)
267                 // that need to be output after the caption.
268                 os << runparams.post_macro;
269                 runparams.post_macro.clear();
270         }
271         // Backwards compatibility: We always had a linebreak after
272         // the caption (see #8514)
273         os << breakln;
274         runparams_in.encoding = runparams.encoding;
275 }
276
277
278 int InsetCaption::plaintext(odocstringstream & os,
279                             OutputParams const & runparams, size_t max_length) const
280 {
281         os << '[' << full_label_ << "\n";
282         InsetText::plaintext(os, runparams, max_length);
283         os << "\n]";
284
285         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
286 }
287
288
289 int InsetCaption::docbook(odocstream & os,
290                           OutputParams const & runparams) const
291 {
292         int ret;
293         os << "<title>";
294         ret = InsetText::docbook(os, runparams);
295         os << "</title>\n";
296         return ret;
297 }
298
299
300 docstring InsetCaption::xhtml(XHTMLStream & xs, OutputParams const & rp) const
301 {
302         if (rp.html_disable_captions)
303                 return docstring();
304         InsetLayout const & il = getLayout();
305         string const & tag = il.htmltag();
306         string attr = il.htmlattr();
307         if (!type_.empty()) {
308                 string const our_class = "float-caption-" + type_;
309                 size_t const loc = attr.find("class='");
310                 if (loc != string::npos)
311                         attr.insert(loc + 7, our_class + " ");
312                 else
313                         attr = attr + " class='" + our_class + "'";
314         }
315         xs << html::StartTag(tag, attr);
316         docstring def = getCaptionAsHTML(xs, rp);
317         xs << html::EndTag(tag);
318         return def;
319 }
320
321
322 void InsetCaption::getArgument(otexstream & os,
323                         OutputParams const & runparams) const
324 {
325         InsetLayout const & il = getLayout();
326
327         if (!il.leftdelim().empty())
328                 os << il.leftdelim();
329
330         OutputParams rp = runparams;
331         if (isPassThru())
332                 rp.pass_thru = true;
333         if (il.isNeedProtect())
334                 rp.moving_arg = true;
335         if (il.isNeedMBoxProtect())
336                 ++rp.inulemcmd;
337         rp.par_begin = 0;
338         rp.par_end = paragraphs().size();
339
340         // Output the contents of the inset
341         if (!paragraphs().empty())
342                 os.texrow().forceStart(paragraphs()[0].id(), 0);
343         latexParagraphs(buffer(), text(), os, rp);
344         runparams.encoding = rp.encoding;
345
346         if (!il.rightdelim().empty())
347                 os << il.rightdelim();
348 }
349
350
351 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
352                         OutputParams const & runparams) const
353 {
354         os << full_label_ << ' ';
355         odocstringstream ods;
356         int const retval = InsetText::plaintext(ods, runparams);
357         os << ods.str();
358         return retval;
359 }
360
361
362 docstring InsetCaption::getCaptionAsHTML(XHTMLStream & xs,
363                         OutputParams const & runparams) const
364 {
365         xs << full_label_ << ' ';
366         InsetText::XHTMLOptions const opts =
367                 InsetText::WriteLabel | InsetText::WriteInnerTag;
368         return InsetText::insetAsXHTML(xs, runparams, opts);
369 }
370
371
372 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
373 {
374         Buffer const & master = *buffer().masterBuffer();
375         DocumentClass const & tclass = master.params().documentClass();
376         string const & lang = it.paragraph().getParLanguage(master.params())->code();
377         Counters & cnts = tclass.counters();
378         string const & type = cnts.current_float();
379         if (utype == OutputUpdate) {
380                 // counters are local to the caption
381                 cnts.saveLastCounter();
382         }
383         // Memorize type for addToToc().
384         floattype_ = type;
385         if (type.empty() || type == "senseless")
386                 full_label_ = master.B_("Senseless!!! ");
387         else {
388                 // FIXME: life would be _much_ simpler if listings was
389                 // listed in Floating.
390                 docstring name;
391                 if (type == "listing")
392                         name = master.B_("Listing");
393                 else
394                         name = master.B_(tclass.floats().getType(type).name());
395                 docstring counter = from_utf8(type);
396                 is_subfloat_ = cnts.isSubfloat();
397                 if (is_subfloat_) {
398                         // only standard captions allowed in subfloats
399                         type_ = "Standard";
400                         counter = "sub-" + from_utf8(type);
401                         name = bformat(_("Sub-%1$s"),
402                                        master.B_(tclass.floats().getType(type).name()));
403                 }
404                 docstring sec;
405                 docstring const lstring = getLayout().labelstring();
406                 docstring const labelstring = isAscii(lstring) ?
407                                 master.B_(to_ascii(lstring)) : lstring;
408                 if (cnts.hasCounter(counter)) {
409                         int val = cnts.value(counter);
410                         // for longtables, we step the counter upstream
411                         if (!cnts.isLongtable())
412                                 cnts.step(counter, utype);
413                         sec = cnts.theCounter(counter, lang);
414                         if (deleted && !cnts.isLongtable())
415                                 // un-step after deleted counter
416                                 cnts.set(counter, val);
417                 }
418                 if (labelstring != master.B_("standard")) {
419                         if (!sec.empty())
420                                 sec += from_ascii(" ");
421                         sec += bformat(from_ascii("(%1$s)"), labelstring);
422                 }
423                 if (!sec.empty())
424                         full_label_ = bformat(from_ascii("%1$s %2$s: "), name, sec);
425                 else
426                         full_label_ = bformat(from_ascii("%1$s #: "), name);
427         }
428
429         // Do the real work now.
430         InsetText::updateBuffer(it, utype, deleted);
431         if (utype == OutputUpdate)
432                 cnts.restoreLastCounter();
433 }
434
435
436 string InsetCaption::contextMenuName() const
437 {
438         return "context-caption";
439 }
440
441
442 } // namespace lyx