]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
f427118e7578a014fb0ce86b56366311516fddbf
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetCaption.h"
30 #include "InsetList.h"
31 #include "Intl.h"
32 #include "Language.h"
33 #include "LaTeXFeatures.h"
34 #include "Lexer.h"
35 #include "lyxfind.h"
36 #include "LyXRC.h"
37 #include "MetricsInfo.h"
38 #include "output_docbook.h"
39 #include "output_latex.h"
40 #include "output_xhtml.h"
41 #include "OutputParams.h"
42 #include "output_plaintext.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "Row.h"
47 #include "sgml.h"
48 #include "TexRow.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53
54 #include "frontends/alert.h"
55 #include "frontends/Painter.h"
56
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60
61 #include "support/bind.h"
62 #include "support/lassert.h"
63
64 using namespace std;
65 using namespace lyx::support;
66
67
68 namespace lyx {
69
70 using graphics::PreviewLoader;
71
72
73 /////////////////////////////////////////////////////////////////////
74
75 InsetText::InsetText(Buffer * buf, UsePlain type)
76         : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
77         text_(this, type == DefaultLayout)
78 {
79 }
80
81
82 InsetText::InsetText(InsetText const & in)
83         : Inset(in), text_(this, in.text_)
84 {
85         drawFrame_ = in.drawFrame_;
86         frame_color_ = in.frame_color_;
87 }
88
89
90 void InsetText::setBuffer(Buffer & buf)
91 {
92         ParagraphList::iterator end = paragraphs().end();
93         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
94                 it->setBuffer(buf);
95         Inset::setBuffer(buf);
96 }
97
98
99 void InsetText::clear()
100 {
101         ParagraphList & pars = paragraphs();
102         LASSERT(!pars.empty(), /**/);
103
104         // This is a gross hack...
105         Layout const & old_layout = pars.begin()->layout();
106
107         pars.clear();
108         pars.push_back(Paragraph());
109         pars.begin()->setInsetOwner(this);
110         pars.begin()->setLayout(old_layout);
111 }
112
113
114 Dimension const InsetText::dimension(BufferView const & bv) const
115 {
116         TextMetrics const & tm = bv.textMetrics(&text_);
117         Dimension dim = tm.dimension();
118         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
119         dim.des += TEXT_TO_INSET_OFFSET;
120         dim.asc += TEXT_TO_INSET_OFFSET;
121         return dim;
122 }
123
124
125 void InsetText::write(ostream & os) const
126 {
127         os << "Text\n";
128         text_.write(os);
129 }
130
131
132 void InsetText::read(Lexer & lex)
133 {
134         clear();
135
136         // delete the initial paragraph
137         Paragraph oldpar = *paragraphs().begin();
138         paragraphs().clear();
139         ErrorList errorList;
140         lex.setContext("InsetText::read");
141         bool res = text_.read(lex, errorList, this);
142
143         if (!res)
144                 lex.printError("Missing \\end_inset at this point. ");
145
146         // sanity check
147         // ensure we have at least one paragraph.
148         if (paragraphs().empty())
149                 paragraphs().push_back(oldpar);
150         // Force default font, if so requested
151         // This avoids paragraphs in buffer language that would have a
152         // foreign language after a document language change, and it ensures
153         // that all new text in ERT and similar gets the "latex" language,
154         // since new text inherits the language from the last position of the
155         // existing text.  As a side effect this makes us also robust against
156         // bugs in LyX that might lead to font changes in ERT in .lyx files.
157         fixParagraphsFont();
158 }
159
160
161 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
162 {
163         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
164
165         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
166
167         // Hand font through to contained lyxtext:
168         tm.font_.fontInfo() = mi.base.font;
169         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
170
171         // This can happen when a layout has a left and right margin,
172         // and the view is made very narrow. We can't do better than 
173         // to draw it partly out of view (bug 5890).
174         if (mi.base.textwidth < 1)
175                 mi.base.textwidth = 1;
176
177         if (hasFixedWidth())
178                 tm.metrics(mi, dim, mi.base.textwidth);
179         else
180                 tm.metrics(mi, dim);
181         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
182         dim.asc += TEXT_TO_INSET_OFFSET;
183         dim.des += TEXT_TO_INSET_OFFSET;
184         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
185 }
186
187
188 void InsetText::draw(PainterInfo & pi, int x, int y) const
189 {
190         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
191
192         if (drawFrame_ || pi.full_repaint) {
193                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
194                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
195                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
196                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
197                 if (pi.full_repaint)
198                         pi.pain.fillRectangle(xframe, yframe, w, h,
199                                 pi.backgroundColor(this));
200
201                 if (drawFrame_)
202                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
203         }
204         ColorCode const old_color = pi.background_color;
205         pi.background_color = pi.backgroundColor(this, false);
206
207         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
208
209         pi.background_color = old_color;
210 }
211
212
213 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
214 {
215         pit_type const pit = front ? 0 : paragraphs().size() - 1;
216         pos_type pos = front ? 0 : paragraphs().back().size();
217
218         // if visual information is not to be ignored, move to extreme right/left
219         if (entry_from != ENTRY_DIRECTION_IGNORE) {
220                 Cursor temp_cur = cur;
221                 temp_cur.pit() = pit;
222                 temp_cur.pos() = pos;
223                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
224                 pos = temp_cur.pos();
225         }
226
227         text_.setCursor(cur.top(), pit, pos);
228         cur.clearSelection();
229         cur.finishUndo();
230 }
231
232
233 Inset * InsetText::editXY(Cursor & cur, int x, int y)
234 {
235         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
236 }
237
238
239 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
240 {
241         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
242                 << " [ cmd.action() = " << cmd.action() << ']');
243
244         if (getLayout().isPassThru()) {
245                 // Force any new text to latex_language FIXME: This
246                 // should only be necessary in constructor, but new
247                 // paragraphs that are created by pressing enter at
248                 // the start of an existing paragraph get the buffer
249                 // language and not latex_language, so we take this
250                 // brute force approach.
251                 cur.current_font.setLanguage(latex_language);
252                 cur.real_current_font.setLanguage(latex_language);
253         }
254
255         switch (cmd.action()) {
256         case LFUN_PASTE:
257         case LFUN_CLIPBOARD_PASTE:
258         case LFUN_SELECTION_PASTE:
259         case LFUN_PRIMARY_SELECTION_PASTE:
260                 text_.dispatch(cur, cmd);
261                 // If we we can only store plain text, we must reset all
262                 // attributes.
263                 // FIXME: Change only the pasted paragraphs
264                 fixParagraphsFont();
265                 break;
266
267         case LFUN_INSET_DISSOLVE: {
268                 bool const main_inset = &buffer().inset() == this;
269                 bool const target_inset = cmd.argument().empty() 
270                         || cmd.getArg(0) == insetName(lyxCode());
271                 bool const one_cell = nargs() == 1;
272
273                 if (!main_inset && target_inset && one_cell) {
274                         // Text::dissolveInset assumes that the cursor
275                         // is inside the Inset.
276                         if (&cur.inset() != this)
277                                 cur.pushBackward(*this);
278                         cur.beginUndoGroup();
279                         text_.dispatch(cur, cmd);
280                         cur.endUndoGroup();
281                 } else
282                         cur.undispatched();
283                 break;
284         }
285
286         default:
287                 text_.dispatch(cur, cmd);
288         }
289         
290         if (!cur.result().dispatched())
291                 Inset::doDispatch(cur, cmd);
292 }
293
294
295 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
296         FuncStatus & status) const
297 {
298         switch (cmd.action()) {
299         case LFUN_INSET_DISSOLVE: {
300                 bool const main_inset = &buffer().inset() == this;
301                 bool const target_inset = cmd.argument().empty() 
302                         || cmd.getArg(0) == insetName(lyxCode());
303                 bool const one_cell = nargs() == 1;
304
305                 if (target_inset)
306                         status.setEnabled(!main_inset && one_cell);
307                 return target_inset;
308         }
309
310         default:
311                 // Dispatch only to text_ if the cursor is inside
312                 // the text_. It is not for context menus (bug 5797).
313                 bool ret = false;
314                 if (cur.text() == &text_)
315                         ret = text_.getStatus(cur, cmd, status);
316                 
317                 if (!ret)
318                         ret = Inset::getStatus(cur, cmd, status);
319                 return ret;
320         }
321 }
322
323
324 void InsetText::fixParagraphsFont()
325 {
326         if (!getLayout().isPassThru())
327                 return;
328
329         Font font(inherit_font, buffer().params().language);
330         font.setLanguage(latex_language);
331         ParagraphList::iterator par = paragraphs().begin();
332         ParagraphList::iterator const end = paragraphs().end();
333         while (par != end) {
334                 par->resetFonts(font);
335                 par->params().clear();
336                 ++par;
337         }
338 }
339
340
341 void InsetText::setChange(Change const & change)
342 {
343         ParagraphList::iterator pit = paragraphs().begin();
344         ParagraphList::iterator end = paragraphs().end();
345         for (; pit != end; ++pit) {
346                 pit->setChange(change);
347         }
348 }
349
350
351 void InsetText::acceptChanges()
352 {
353         text_.acceptChanges();
354 }
355
356
357 void InsetText::rejectChanges()
358 {
359         text_.rejectChanges();
360 }
361
362
363 void InsetText::validate(LaTeXFeatures & features) const
364 {
365         features.useInsetLayout(getLayout());
366         for_each(paragraphs().begin(), paragraphs().end(),
367                  bind(&Paragraph::validate, _1, ref(features)));
368 }
369
370
371 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
372 {
373         // This implements the standard way of handling the LaTeX
374         // output of a text inset, either a command or an
375         // environment. Standard collapsable insets should not
376         // redefine this, non-standard ones may call this.
377         InsetLayout const & il = getLayout();
378         int rows = 0;
379         if (!il.latexname().empty()) {
380                 if (il.latextype() == InsetLayout::COMMAND) {
381                         // FIXME UNICODE
382                         if (runparams.moving_arg)
383                                 os << "\\protect";
384                         os << '\\' << from_utf8(il.latexname());
385                         if (!il.latexparam().empty())
386                                 os << from_utf8(il.latexparam());
387                         os << '{';
388                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
389                         os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
390                         if (!il.latexparam().empty())
391                                 os << from_utf8(il.latexparam());
392                         rows += 2;
393                 }
394         }
395         OutputParams rp = runparams;
396         if (il.isPassThru())
397                 rp.verbatim = true;
398         if (il.isNeedProtect())
399                 rp.moving_arg = true;
400
401         // Output the contents of the inset
402         TexRow texrow;
403         latexParagraphs(buffer(), text_, os, texrow, rp);
404         rows += texrow.rows();
405
406         if (!il.latexname().empty()) {
407                 if (il.latextype() == InsetLayout::COMMAND) {
408                         os << "}";
409                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
410                         os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
411                         rows += 2;
412                 }
413         }
414         return rows;
415 }
416
417
418 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
419 {
420         ParagraphList::const_iterator beg = paragraphs().begin();
421         ParagraphList::const_iterator end = paragraphs().end();
422         ParagraphList::const_iterator it = beg;
423         bool ref_printed = false;
424         int len = 0;
425         for (; it != end; ++it) {
426                 if (it != beg) {
427                         os << '\n';
428                         if (runparams.linelen > 0)
429                                 os << '\n';
430                 }
431                 odocstringstream oss;
432                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
433                 docstring const str = oss.str();
434                 os << str;
435                 // FIXME: len is not computed fully correctly; in principle,
436                 // we have to count the characters after the last '\n'
437                 len = str.size();
438         }
439
440         return len;
441 }
442
443
444 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
445 {
446         ParagraphList::const_iterator const beg = paragraphs().begin();
447
448         if (!undefined())
449                 sgml::openTag(os, getLayout().latexname(),
450                               beg->getID(buffer(), runparams) + getLayout().latexparam());
451
452         docbookParagraphs(text_, buffer(), os, runparams);
453
454         if (!undefined())
455                 sgml::closeTag(os, getLayout().latexname());
456
457         return 0;
458 }
459
460
461 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
462 {
463         return insetAsXHTML(xs, runparams, WriteEverything);
464 }
465
466
467 // FIXME XHTML
468 // There are cases where we may need to close open fonts and such
469 // and then re-open them when we are done. This would be the case, e.g.,
470 // if we were otherwise about to write:
471 //              <em>word <div class='foot'>footnote text.</div> emph</em>
472 // The problem isn't so much that the footnote text will get emphasized:
473 // we can handle that with CSS. The problem is that this is invalid XHTML.
474 // One solution would be to make the footnote <span>, but the problem is
475 // completely general, and so we'd have to make absolutely everything into
476 // span. What I think will work is to check if we're about to write "div" and,
477 // if so, try to close fonts, etc. 
478 // There are probably limits to how well we can do here, though, and we will
479 // have to rely upon users not putting footnotes inside noun-type insets.
480 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & runparams,
481                                   XHTMLOptions opts) const
482 {
483         if (undefined()) {
484                 xhtmlParagraphs(text_, buffer(), xs, runparams);
485                 return docstring();
486         }
487
488         InsetLayout const & il = getLayout();
489         if (opts & WriteOuterTag)
490                 xs << html::StartTag(il.htmltag(), il.htmlattr());
491         if ((opts & WriteLabel) && !il.counter().empty()) {
492                 BufferParams const & bp = buffer().masterBuffer()->params();
493                 Counters & cntrs = bp.documentClass().counters();
494                 cntrs.step(il.counter(), OutputUpdate);
495                 // FIXME: translate to paragraph language
496                 if (!il.htmllabel().empty()) {
497                         docstring const lbl = 
498                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
499                         // FIXME is this check necessary?
500                         if (!lbl.empty()) {
501                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
502                                 xs << lbl;
503                                 xs << html::EndTag(il.htmllabeltag());
504                         }
505                 }
506         }
507
508         if (opts & WriteInnerTag)
509                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
510         OutputParams ours = runparams;
511         if (!il.isMultiPar() || opts == JustText)
512                 ours.html_make_pars = false;
513         xhtmlParagraphs(text_, buffer(), xs, ours);
514         if (opts & WriteInnerTag)
515                 xs << html::EndTag(il.htmlinnertag());
516         if (opts & WriteOuterTag)
517                 xs << html::EndTag(il.htmltag());
518         return docstring();
519 }
520
521
522 void InsetText::cursorPos(BufferView const & bv,
523                 CursorSlice const & sl, bool boundary, int & x, int & y) const
524 {
525         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
526         y = bv.textMetrics(&text_).cursorY(sl, boundary);
527 }
528
529
530 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
531 {
532         clear();
533         Paragraph & first = paragraphs().front();
534         for (unsigned int i = 0; i < data.length(); ++i)
535                 first.insertChar(i, data[i], font, trackChanges);
536 }
537
538
539 void InsetText::setAutoBreakRows(bool flag)
540 {
541         if (flag == text_.autoBreakRows_)
542                 return;
543
544         text_.autoBreakRows_ = flag;
545         if (flag)
546                 return;
547
548         // remove previously existing newlines
549         ParagraphList::iterator it = paragraphs().begin();
550         ParagraphList::iterator end = paragraphs().end();
551         for (; it != end; ++it)
552                 for (int i = 0; i < it->size(); ++i)
553                         if (it->isNewline(i))
554                                 // do not track the change, because the user
555                                 // is not allowed to revert/reject it
556                                 it->eraseChar(i, false);
557 }
558
559
560 void InsetText::setDrawFrame(bool flag)
561 {
562         drawFrame_ = flag;
563 }
564
565
566 ColorCode InsetText::frameColor() const
567 {
568         return frame_color_;
569 }
570
571
572 void InsetText::setFrameColor(ColorCode col)
573 {
574         frame_color_ = col;
575 }
576
577
578 void InsetText::appendParagraphs(ParagraphList & plist)
579 {
580         // There is little we can do here to keep track of changes.
581         // As of 2006/10/20, appendParagraphs is used exclusively by
582         // LyXTabular::setMultiColumn. In this context, the paragraph break
583         // is lost irreversibly and the appended text doesn't really change
584
585         ParagraphList & pl = paragraphs();
586
587         ParagraphList::iterator pit = plist.begin();
588         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
589         ++pit;
590         mergeParagraph(buffer().params(), pl,
591                        distance(pl.begin(), ins) - 1);
592
593         for_each(pit, plist.end(),
594                  bind(&ParagraphList::push_back, ref(pl), _1));
595 }
596
597
598 void InsetText::addPreview(DocIterator const & text_inset_pos,
599         PreviewLoader & loader) const
600 {
601         ParagraphList::const_iterator pit = paragraphs().begin();
602         ParagraphList::const_iterator pend = paragraphs().end();
603         int pidx = 0;
604
605         DocIterator inset_pos = text_inset_pos;
606         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
607
608         for (; pit != pend; ++pit, ++pidx) {
609                 InsetList::const_iterator it  = pit->insetList().begin();
610                 InsetList::const_iterator end = pit->insetList().end();
611                 inset_pos.pit() = pidx;
612                 for (; it != end; ++it) {
613                         inset_pos.pos() = it->pos;
614                         it->inset->addPreview(inset_pos, loader);
615                 }
616         }
617 }
618
619
620 ParagraphList const & InsetText::paragraphs() const
621 {
622         return text_.paragraphs();
623 }
624
625
626 ParagraphList & InsetText::paragraphs()
627 {
628         return text_.paragraphs();
629 }
630
631
632 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
633 {
634         ParIterator it2 = it;
635         it2.forwardPos();
636         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
637         if (producesOutput()) {
638                 InsetLayout const & il = getLayout();
639                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
640                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
641                 if (save_layouts) {
642                         // LYXERR0("Entering " << name());
643                         cnt.clearLastLayout();
644                         // FIXME cnt.saveLastCounter()?
645                 }
646                 buffer().updateBuffer(it2, utype);
647                 if (save_layouts) {
648                         // LYXERR0("Exiting " << name());
649                         cnt.restoreLastLayout();
650                         // FIXME cnt.restoreLastCounter()?
651                 }
652         } else {
653                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
654                 // Note that we do not need to call:
655                 //      tclass.counters().clearLastLayout()
656                 // since we are saving and restoring the existing counters, etc.
657                 Counters const savecnt = tclass.counters();
658                 buffer().updateBuffer(it2, utype);
659                 tclass.counters() = savecnt;
660         }
661 }
662
663
664 void InsetText::tocString(odocstream & os) const
665 {
666         if (!getLayout().isInToc())
667                 return;
668         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
669 }
670
671
672
673 void InsetText::addToToc(DocIterator const & cdit)
674 {
675         DocIterator dit = cdit;
676         dit.push_back(CursorSlice(*this));
677         Toc & toc = buffer().tocBackend().toc("tableofcontents");
678
679         BufferParams const & bufparams = buffer_->params();
680         const int min_toclevel = bufparams.documentClass().min_toclevel();
681
682         // For each paragraph, traverse its insets and let them add
683         // their toc items
684         ParagraphList & pars = paragraphs();
685         pit_type pend = paragraphs().size();
686         for (pit_type pit = 0; pit != pend; ++pit) {
687                 Paragraph const & par = pars[pit];
688                 dit.pit() = pit;
689                 // the string that goes to the toc (could be the optarg)
690                 docstring tocstring;
691                 InsetList::const_iterator it  = par.insetList().begin();
692                 InsetList::const_iterator end = par.insetList().end();
693                 for (; it != end; ++it) {
694                         Inset & inset = *it->inset;
695                         dit.pos() = it->pos;
696                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
697                         inset.addToToc(dit);
698                         switch (inset.lyxCode()) {
699                         case OPTARG_CODE: {
700                                 if (!tocstring.empty())
701                                         break;
702                                 dit.pos() = 0;
703                                 Paragraph const & insetpar =
704                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
705                                 if (!par.labelString().empty())
706                                         tocstring = par.labelString() + ' ';
707                                 tocstring += insetpar.asString(AS_STR_INSETS);
708                                 break;
709                         }
710                         default:
711                                 break;
712                         }
713                 }
714                 // now the toc entry for the paragraph
715                 int const toclevel = par.layout().toclevel;
716                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
717                         dit.pos() = 0;
718                         // insert this into the table of contents
719                         if (tocstring.empty())
720                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
721                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
722                 }
723                 
724                 // And now the list of changes.
725                 par.addChangesToToc(dit, buffer());
726         }
727 }
728
729
730 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
731 {
732         if (buffer().isClean())
733                 return Inset::notifyCursorLeaves(old, cur);
734         
735         // find text inset in old cursor
736         Cursor insetCur = old;
737         int scriptSlice = insetCur.find(this);
738         LASSERT(scriptSlice != -1, /**/);
739         insetCur.cutOff(scriptSlice);
740         LASSERT(&insetCur.inset() == this, /**/);
741         
742         // update the old paragraph's words
743         insetCur.paragraph().updateWords();
744         
745         return Inset::notifyCursorLeaves(old, cur);
746 }
747
748
749 bool InsetText::completionSupported(Cursor const & cur) const
750 {
751         //LASSERT(&cur.bv().cursor().inset() != this, return false);
752         return text_.completionSupported(cur);
753 }
754
755
756 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
757 {
758         return completionSupported(cur);
759 }
760
761
762 bool InsetText::automaticInlineCompletion() const
763 {
764         return lyxrc.completion_inline_text;
765 }
766
767
768 bool InsetText::automaticPopupCompletion() const
769 {
770         return lyxrc.completion_popup_text;
771 }
772
773
774 bool InsetText::showCompletionCursor() const
775 {
776         return lyxrc.completion_cursor_text;
777 }
778
779
780 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
781 {
782         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
783 }
784
785
786 docstring InsetText::completionPrefix(Cursor const & cur) const
787 {
788         if (!completionSupported(cur))
789                 return docstring();
790         return text_.completionPrefix(cur);
791 }
792
793
794 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
795         bool finished)
796 {
797         if (!completionSupported(cur))
798                 return false;
799
800         return text_.insertCompletion(cur, s, finished);
801 }
802
803
804 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
805         Dimension & dim) const
806 {
807         TextMetrics const & tm = cur.bv().textMetrics(&text_);
808         tm.completionPosAndDim(cur, x, y, dim);
809 }
810
811
812 docstring InsetText::contextMenu(BufferView const &, int, int) const
813 {
814         return from_ascii("context-edit");
815 }
816
817
818 InsetCaption const * InsetText::getCaptionInset() const
819 {
820         ParagraphList::const_iterator pit = paragraphs().begin();
821         for (; pit != paragraphs().end(); ++pit) {
822                 InsetList::const_iterator it = pit->insetList().begin();
823                 for (; it != pit->insetList().end(); ++it) {
824                         Inset & inset = *it->inset;
825                         if (inset.lyxCode() == CAPTION_CODE) {
826                                 InsetCaption const * ins =
827                                         static_cast<InsetCaption const *>(it->inset);
828                                 return ins;
829                         }
830                 }
831         }
832         return 0;
833 }
834
835
836 docstring InsetText::getCaptionText(OutputParams const & runparams) const
837 {
838         InsetCaption const * ins = getCaptionInset();
839         if (ins == 0)
840                 return docstring();
841
842         odocstringstream ods;
843         ins->getCaptionAsPlaintext(ods, runparams);
844         return ods.str();
845 }
846
847
848 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
849 {
850         InsetCaption const * ins = getCaptionInset();
851         if (ins == 0)
852                 return docstring();
853
854         odocstringstream ods;
855         XHTMLStream xs(ods);
856         docstring def = ins->getCaptionAsHTML(xs, runparams);
857         if (!def.empty())
858                 // should already have been escaped
859                 xs << XHTMLStream::NextRaw() << def << '\n';
860         return ods.str();
861 }
862
863
864 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
865 {
866         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
867 }
868
869 } // namespace lyx