]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Natbib authoryear uses (Ref1; Ref2) by default.
[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 "Counters.h"
21 #include "Cursor.h"
22 #include "Dimension.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "InsetList.h"
28 #include "Language.h"
29 #include "MetricsInfo.h"
30 #include "output_latex.h"
31 #include "output_xhtml.h"
32 #include "OutputParams.h"
33 #include "Paragraph.h"
34 #include "TextClass.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
37
38 #include "frontends/FontMetrics.h"
39 #include "frontends/Painter.h"
40
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43
44 #include <sstream>
45
46 using namespace std;
47 using namespace lyx::support;
48
49 namespace lyx {
50
51
52 InsetCaption::InsetCaption(Buffer * buf, string const & type)
53     : InsetText(buf, InsetText::PlainLayout), type_(type)
54 {
55         setAutoBreakRows(true);
56         setDrawFrame(true);
57         setFrameColor(Color_collapsableframe);
58 }
59
60
61 void InsetCaption::write(ostream & os) const
62 {
63         os << "Caption";
64         if (!type_.empty()) {
65                 os << " "
66                    << type_;
67         }
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::setCustomLabel(docstring const & label)
90 {
91         if (!isAscii(label) || label.empty())
92                 // This must be a user defined layout. We cannot translate
93                 // this, since gettext accepts only ascii keys.
94                 custom_label_ = label;
95         else
96                 custom_label_ = _(to_ascii(label));
97 }
98
99
100 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active) const
101 {
102         if (floattype_.empty())
103                 return;
104
105         DocIterator pit = cpit;
106         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
107
108         Toc & toc = buffer().tocBackend().toc(floattype_);
109         docstring str = full_label_;
110         int length = output_active ? INT_MAX : TOC_ENTRY_LENGTH;
111         text().forToc(str, length);
112         toc.push_back(TocItem(pit, 0, str, output_active));
113
114         // Proceed with the rest of the inset.
115         InsetText::addToToc(cpit, output_active);
116 }
117
118
119 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
120 {
121         FontInfo tmpfont = mi.base.font;
122         mi.base.font = mi.base.bv->buffer().params().getFont().fontInfo();
123         labelwidth_ = theFontMetrics(mi.base.font).width(full_label_);
124         // add some space to separate the label from the inset text
125         labelwidth_ += 2 * TEXT_TO_INSET_OFFSET;
126         dim.wid = labelwidth_;
127         Dimension textdim;
128         // Correct for button and label width
129         mi.base.textwidth -= dim.wid;
130         InsetText::metrics(mi, textdim);
131         mi.base.font = tmpfont;
132         mi.base.textwidth += dim.wid;
133         dim.des = max(dim.des - textdim.asc + dim.asc, textdim.des);
134         dim.asc = textdim.asc;
135         dim.wid += textdim.wid;
136 }
137
138
139 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
140 {
141         TextMetrics & tm = pi.base.bv->textMetrics(&text());
142         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
143         int const yy = y - TEXT_TO_INSET_OFFSET - tm.ascent();
144         pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
145 }
146
147
148 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
149 {
150         // We must draw the label, we should get the label string
151         // from the enclosing float inset.
152         // The question is: Who should draw the label, the caption inset,
153         // the text inset or the paragraph?
154         // We should also draw the float number (Lgb)
155
156         // Answer: the text inset (in buffer_funcs.cpp: setCaption).
157
158         FontInfo tmpfont = pi.base.font;
159         pi.base.font = pi.base.bv->buffer().params().getFont().fontInfo();
160         pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
161         int const xx = x + TEXT_TO_INSET_OFFSET;
162         pi.pain.text(xx, y, full_label_, pi.base.font);
163         InsetText::draw(pi, x + labelwidth_, y);
164         pi.base.font = tmpfont;
165 }
166
167
168 void InsetCaption::edit(Cursor & cur, bool front, EntryDirection entry_from)
169 {
170         cur.push(*this);
171         InsetText::edit(cur, front, entry_from);
172 }
173
174
175 Inset * InsetCaption::editXY(Cursor & cur, int x, int y)
176 {
177         cur.push(*this);
178         return InsetText::editXY(cur, x, y);
179 }
180
181
182 bool InsetCaption::insetAllowed(InsetCode code) const
183 {
184         switch (code) {
185         // code that is not allowed in a caption
186         case CAPTION_CODE:
187         case FLOAT_CODE:
188         case FOOT_CODE:
189         case NEWPAGE_CODE:
190         case MARGIN_CODE:
191         case MATHMACRO_CODE:
192         case TABULAR_CODE:
193         case WRAP_CODE:
194                 return false;
195         default:
196                 return InsetText::insetAllowed(code);
197         }
198 }
199
200
201 void InsetCaption::doDispatch(Cursor & cur, FuncRequest & cmd)
202 {
203         switch (cmd.action()) {
204
205         case LFUN_INSET_MODIFY: {
206                 string const first_arg = cmd.getArg(0);
207                 bool const change_type = first_arg == "changetype";
208                 if (change_type) {
209                         cur.recordUndoInset(ATOMIC_UNDO, this);
210                         type_ = cmd.getArg(1);
211                         cur.forceBufferUpdate();
212                         break;
213                 }
214         }
215
216         default:
217                 InsetText::doDispatch(cur, cmd);
218                 break;
219         }
220 }
221
222
223 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
224         FuncStatus & status) const
225 {
226         switch (cmd.action()) {
227
228         case LFUN_INSET_MODIFY: {
229                 string const first_arg = cmd.getArg(0);
230                 if (first_arg == "changetype") {
231                         string const type = cmd.getArg(1);
232                         status.setOnOff(type == type_);
233                         bool varia = type != "LongTableNoNumber";
234                         // check if the immediate parent inset allows caption variation
235                         if (cur.depth() > 1) {
236                                 if (&cur[cur.depth() - 2].inset())
237                                         varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
238                         }
239                         status.setEnabled(varia
240                                           && buffer().params().documentClass().hasInsetLayout(
241                                                 from_ascii("Caption:" + type)));
242                         return true;
243                 }
244                 return InsetText::getStatus(cur, cmd, status);
245         }
246
247         case LFUN_PARAGRAPH_BREAK:
248                 status.setEnabled(false);
249                 return true;
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         // FIXME: actually, it is moving only when there is no
275         // optional argument.
276         runparams.moving_arg = !runparams.inTableCell;
277         InsetText::latex(os, runparams);
278         runparams_in.encoding = runparams.encoding;
279 }
280
281
282 int InsetCaption::plaintext(odocstringstream & os,
283                             OutputParams const & runparams, size_t max_length) const
284 {
285         os << '[' << full_label_ << "\n";
286         InsetText::plaintext(os, runparams, max_length);
287         os << "\n]";
288
289         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
290 }
291
292
293 int InsetCaption::docbook(odocstream & os,
294                           OutputParams const & runparams) const
295 {
296         int ret;
297         os << "<title>";
298         ret = InsetText::docbook(os, runparams);
299         os << "</title>\n";
300         return ret;
301 }
302
303
304 docstring InsetCaption::xhtml(XHTMLStream & xs, OutputParams const & rp) const
305 {
306         if (rp.html_disable_captions)
307                 return docstring();
308         InsetLayout const & il = getLayout();
309         string const tag = il.htmltag();
310         string attr = il.htmlattr();
311         if (!type_.empty()) {
312                 string const our_class = "float-caption-" + type_;
313                 size_t const loc = attr.find("class='");
314                 if (loc != string::npos)
315                         attr.insert(loc + 1, our_class);
316         }
317         xs << html::StartTag(tag, attr);
318         docstring def = getCaptionAsHTML(xs, rp);
319         xs << html::EndTag(tag);
320         return def;
321 }
322
323
324 void InsetCaption::getArgument(otexstream & os,
325                         OutputParams const & runparams) const
326 {
327         InsetLayout const & il = getLayout();
328
329         if (!il.leftdelim().empty())
330                 os << il.leftdelim();
331   
332         OutputParams rp = runparams;
333         if (isPassThru())
334                 rp.pass_thru = true;
335         if (il.isNeedProtect())
336                 rp.moving_arg = true;
337         rp.par_begin = 0;
338         rp.par_end = paragraphs().size();
339
340         // Output the contents of the inset
341         latexParagraphs(buffer(), text(), os, rp);
342         runparams.encoding = rp.encoding;
343
344         if (!il.rightdelim().empty())
345                 os << il.rightdelim();
346 }
347
348
349 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
350                         OutputParams const & runparams) const
351 {
352         os << full_label_ << ' ';
353         odocstringstream ods;
354         int const retval = InsetText::plaintext(ods, runparams);
355         os << ods.str();
356         return retval;
357 }
358
359
360 docstring InsetCaption::getCaptionAsHTML(XHTMLStream & xs,
361                         OutputParams const & runparams) const
362 {
363         xs << full_label_ << ' ';
364         InsetText::XHTMLOptions const opts = 
365                 InsetText::WriteLabel | InsetText::WriteInnerTag;
366         return InsetText::insetAsXHTML(xs, runparams, opts);
367 }
368
369
370 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype)
371 {
372         Buffer const & master = *buffer().masterBuffer();
373         DocumentClass const & tclass = master.params().documentClass();
374         string const & lang = it.paragraph().getParLanguage(master.params())->code();
375         Counters & cnts = tclass.counters();
376         string const & type = cnts.current_float();
377         if (utype == OutputUpdate) {
378                 // counters are local to the caption
379                 cnts.saveLastCounter();
380         }
381         // Memorize type for addToToc().
382         floattype_ = type;
383         if (type.empty())
384                 full_label_ = master.B_("Senseless!!! ");
385         else {
386                 // FIXME: life would be _much_ simpler if listings was
387                 // listed in Floating.
388                 docstring name;
389                 if (type == "listing")
390                         name = master.B_("Listing");
391                 else
392                         name = master.B_(tclass.floats().getType(type).name());
393                 docstring counter = from_utf8(type);
394                 if (cnts.isSubfloat()) {
395                         // only standard captions allowed in subfloats
396                         type_ = "Standard";
397                         counter = "sub-" + from_utf8(type);
398                         name = bformat(_("Sub-%1$s"),
399                                        master.B_(tclass.floats().getType(type).name()));
400                 }
401                 docstring sec;
402                 if (cnts.hasCounter(counter)) {
403                         cnts.step(counter, utype);
404                         sec = cnts.theCounter(counter, lang);
405                 }
406                 if (getLayout().labelstring() != master.B_("standard")) {
407                         if (!sec.empty())
408                                 sec += from_ascii(" ");
409                         sec += bformat(from_ascii("(%1$s)"), getLayout().labelstring());
410                 }
411                 if (!sec.empty())
412                         full_label_ = bformat(from_ascii("%1$s %2$s:"), name, sec);
413                 else
414                         full_label_ = bformat(from_ascii("%1$s #:"), name);
415         }
416
417         // Do the real work now.
418         InsetText::updateBuffer(it, utype);
419         if (utype == OutputUpdate)
420                 cnts.restoreLastCounter();
421 }
422
423
424 string InsetCaption::contextMenuName() const
425 {
426         return "context-caption";
427 }
428
429
430 } // namespace lyx