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