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