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