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