]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Use isMainText() instead of doing explicit tests
[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.finishUndo();
255 }
256
257
258 Inset * InsetText::editXY(Cursor & cur, int x, int y)
259 {
260         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
261 }
262
263
264 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
265 {
266         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
267
268         // See bug #9042, for instance.
269         if (isPassThru() && lyxCode() != ARG_CODE) {
270                 // Force any new text to latex_language FIXME: This
271                 // should only be necessary in constructor, but new
272                 // paragraphs that are created by pressing enter at
273                 // the start of an existing paragraph get the buffer
274                 // language and not latex_language, so we take this
275                 // brute force approach.
276                 cur.current_font.setLanguage(latex_language);
277                 cur.real_current_font.setLanguage(latex_language);
278         }
279
280         switch (cmd.action()) {
281         case LFUN_PASTE:
282         case LFUN_CLIPBOARD_PASTE:
283         case LFUN_SELECTION_PASTE:
284         case LFUN_PRIMARY_SELECTION_PASTE:
285                 text_.dispatch(cur, cmd);
286                 // If we we can only store plain text, we must reset all
287                 // attributes.
288                 // FIXME: Change only the pasted paragraphs
289                 fixParagraphsFont();
290                 break;
291
292         case LFUN_INSET_DISSOLVE: {
293                 bool const main_inset = text_.isMainText();
294                 bool const target_inset = cmd.argument().empty() 
295                         || cmd.getArg(0) == insetName(lyxCode());
296                 // cur.inset() is the tabular when this is a single cell (bug #9954)
297                 bool const one_cell = cur.inset().nargs() == 1;
298
299                 if (!main_inset && target_inset && one_cell) {
300                         // Text::dissolveInset assumes that the cursor
301                         // is inside the Inset.
302                         if (&cur.inset() != this)
303                                 cur.pushBackward(*this);
304                         cur.beginUndoGroup();
305                         text_.dispatch(cur, cmd);
306                         cur.endUndoGroup();
307                 } else
308                         cur.undispatched();
309                 break;
310         }
311
312         default:
313                 text_.dispatch(cur, cmd);
314         }
315         
316         if (!cur.result().dispatched())
317                 Inset::doDispatch(cur, cmd);
318 }
319
320
321 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
322         FuncStatus & status) const
323 {
324         switch (cmd.action()) {
325         case LFUN_INSET_DISSOLVE: {
326                 bool const main_inset = text_.isMainText();
327                 bool const target_inset = cmd.argument().empty() 
328                         || cmd.getArg(0) == insetName(lyxCode());
329                 // cur.inset() is the tabular when this is a single cell (bug #9954)
330                 bool const one_cell = cur.inset().nargs() == 1;
331
332                 if (target_inset)
333                         status.setEnabled(!main_inset && one_cell);
334                 return target_inset;
335         }
336
337         case LFUN_ARGUMENT_INSERT: {
338                 string const arg = cmd.getArg(0);
339                 if (arg.empty()) {
340                         status.setEnabled(false);
341                         return true;
342                 }
343                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
344                         return text_.getStatus(cur, cmd, status);
345
346                 Layout::LaTeXArgMap args = getLayout().args();
347                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
348                 if (lait != args.end()) {
349                         status.setEnabled(true);
350                         ParagraphList::const_iterator pit = paragraphs().begin();
351                         for (; pit != paragraphs().end(); ++pit) {
352                                 InsetList::const_iterator it = pit->insetList().begin();
353                                 InsetList::const_iterator end = pit->insetList().end();
354                                 for (; it != end; ++it) {
355                                         if (it->inset->lyxCode() == ARG_CODE) {
356                                                 InsetArgument const * ins =
357                                                         static_cast<InsetArgument const *>(it->inset);
358                                                 if (ins->name() == arg) {
359                                                         // we have this already
360                                                         status.setEnabled(false);
361                                                         return true;
362                                                 }
363                                         }
364                                 }
365                         }
366                 } else
367                         status.setEnabled(false);
368                 return true;
369         }
370
371         default:
372                 // Dispatch only to text_ if the cursor is inside
373                 // the text_. It is not for context menus (bug 5797).
374                 bool ret = false;
375                 if (cur.text() == &text_)
376                         ret = text_.getStatus(cur, cmd, status);
377                 
378                 if (!ret)
379                         ret = Inset::getStatus(cur, cmd, status);
380                 return ret;
381         }
382 }
383
384
385 void InsetText::fixParagraphsFont()
386 {
387         Font font(inherit_font, buffer().params().language);
388         font.setLanguage(latex_language);
389         ParagraphList::iterator par = paragraphs().begin();
390         ParagraphList::iterator const end = paragraphs().end();
391         while (par != end) {
392                 if (par->isPassThru())
393                         par->resetFonts(font);
394                 if (!par->allowParagraphCustomization())
395                         par->params().clear();
396                 ++par;
397         }
398 }
399
400
401 void InsetText::setChange(Change const & change)
402 {
403         ParagraphList::iterator pit = paragraphs().begin();
404         ParagraphList::iterator end = paragraphs().end();
405         for (; pit != end; ++pit) {
406                 pit->setChange(change);
407         }
408 }
409
410
411 void InsetText::acceptChanges()
412 {
413         text_.acceptChanges();
414 }
415
416
417 void InsetText::rejectChanges()
418 {
419         text_.rejectChanges();
420 }
421
422
423 void InsetText::validate(LaTeXFeatures & features) const
424 {
425         features.useInsetLayout(getLayout());
426         for_each(paragraphs().begin(), paragraphs().end(),
427                  bind(&Paragraph::validate, _1, ref(features)));
428 }
429
430
431 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
432 {
433         // This implements the standard way of handling the LaTeX
434         // output of a text inset, either a command or an
435         // environment. Standard collapsable insets should not
436         // redefine this, non-standard ones may call this.
437         InsetLayout const & il = getLayout();
438         if (il.forceOwnlines())
439                 os << breakln;
440         if (!il.latexname().empty()) {
441                 if (il.latextype() == InsetLayout::COMMAND) {
442                         // FIXME UNICODE
443                         // FIXME \protect should only be used for fragile
444                         //    commands, but we do not provide this information yet.
445                         if (runparams.moving_arg)
446                                 os << "\\protect";
447                         os << '\\' << from_utf8(il.latexname());
448                         if (!il.latexargs().empty())
449                                 getArgs(os, runparams);
450                         if (!il.latexparam().empty())
451                                 os << from_utf8(il.latexparam());
452                         os << '{';
453                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
454                         if (il.isDisplay())
455                                 os << breakln;
456                         else
457                                 os << safebreakln;
458                         if (runparams.lastid != -1)
459                                 os.texrow().start(runparams.lastid,
460                                                   runparams.lastpos);
461                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
462                         if (!il.latexargs().empty())
463                                 getArgs(os, runparams);
464                         if (!il.latexparam().empty())
465                                 os << from_utf8(il.latexparam());
466                         os << '\n';
467                 }
468         } else {
469                 if (!il.latexargs().empty())
470                         getArgs(os, runparams);
471                 if (!il.latexparam().empty())
472                         os << from_utf8(il.latexparam());
473         }
474
475         if (!il.leftdelim().empty())
476                 os << il.leftdelim();
477
478         OutputParams rp = runparams;
479         if (isPassThru())
480                 rp.pass_thru = true;
481         if (il.isNeedProtect())
482                 rp.moving_arg = true;
483         if (!il.passThruChars().empty())
484                 rp.pass_thru_chars += il.passThruChars();
485         rp.par_begin = 0;
486         rp.par_end = paragraphs().size();
487
488         // Output the contents of the inset
489         latexParagraphs(buffer(), text_, os, rp);
490         runparams.encoding = rp.encoding;
491
492         if (!il.rightdelim().empty())
493                 os << il.rightdelim();
494
495         if (!il.latexname().empty()) {
496                 if (il.latextype() == InsetLayout::COMMAND) {
497                         os << "}";
498                         if (!il.postcommandargs().empty())
499                                 getArgs(os, runparams, true);
500                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
501                         // A comment environment doesn't need a % before \n\end
502                         if (il.isDisplay() || runparams.inComment)
503                                 os << breakln;
504                         else
505                                 os << safebreakln;
506                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
507                         if (!il.isDisplay())
508                                 os.protectSpace(true);
509                 }
510         }
511         if (il.forceOwnlines())
512                 os << breakln;
513 }
514
515
516 int InsetText::plaintext(odocstringstream & os,
517         OutputParams const & runparams, size_t max_length) const
518 {
519         ParagraphList::const_iterator beg = paragraphs().begin();
520         ParagraphList::const_iterator end = paragraphs().end();
521         ParagraphList::const_iterator it = beg;
522         bool ref_printed = false;
523         int len = 0;
524         for (; it != end; ++it) {
525                 if (it != beg) {
526                         os << '\n';
527                         if (runparams.linelen > 0)
528                                 os << '\n';
529                 }
530                 odocstringstream oss;
531                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
532                 docstring const str = oss.str();
533                 os << str;
534                 // FIXME: len is not computed fully correctly; in principle,
535                 // we have to count the characters after the last '\n'
536                 len = str.size();
537                 if (os.str().size() >= max_length)
538                         break;
539         }
540
541         return len;
542 }
543
544
545 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
546 {
547         ParagraphList::const_iterator const beg = paragraphs().begin();
548
549         if (!undefined())
550                 sgml::openTag(os, getLayout().latexname(),
551                               beg->getID(buffer(), runparams) + getLayout().latexparam());
552
553         docbookParagraphs(text_, buffer(), os, runparams);
554
555         if (!undefined())
556                 sgml::closeTag(os, getLayout().latexname());
557
558         return 0;
559 }
560
561
562 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
563 {
564         return insetAsXHTML(xs, runparams, WriteEverything);
565 }
566
567
568 // FIXME XHTML
569 // There are cases where we may need to close open fonts and such
570 // and then re-open them when we are done. This would be the case, e.g.,
571 // if we were otherwise about to write:
572 //              <em>word <div class='foot'>footnote text.</div> emph</em>
573 // The problem isn't so much that the footnote text will get emphasized:
574 // we can handle that with CSS. The problem is that this is invalid XHTML.
575 // One solution would be to make the footnote <span>, but the problem is
576 // completely general, and so we'd have to make absolutely everything into
577 // span. What I think will work is to check if we're about to write "div" and,
578 // if so, try to close fonts, etc. 
579 // There are probably limits to how well we can do here, though, and we will
580 // have to rely upon users not putting footnotes inside noun-type insets.
581 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
582                                   XHTMLOptions opts) const
583 {
584         // we will always want to output all our paragraphs when we are
585         // called this way.
586         OutputParams runparams = rp;
587         runparams.par_begin = 0;
588         runparams.par_end = text().paragraphs().size();
589         
590         if (undefined()) {
591                 xhtmlParagraphs(text_, buffer(), xs, runparams);
592                 return docstring();
593         }
594
595         InsetLayout const & il = getLayout();
596         if (opts & WriteOuterTag)
597                 xs << html::StartTag(il.htmltag(), il.htmlattr());
598
599         if ((opts & WriteLabel) && !il.counter().empty()) {
600                 BufferParams const & bp = buffer().masterBuffer()->params();
601                 Counters & cntrs = bp.documentClass().counters();
602                 cntrs.step(il.counter(), OutputUpdate);
603                 // FIXME: translate to paragraph language
604                 if (!il.htmllabel().empty()) {
605                         docstring const lbl = 
606                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
607                         // FIXME is this check necessary?
608                         if (!lbl.empty()) {
609                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
610                                 xs << lbl;
611                                 xs << html::EndTag(il.htmllabeltag());
612                         }
613                 }
614         }
615
616         if (opts & WriteInnerTag)
617                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
618
619         // we will eventually lose information about the containing inset
620         if (!allowMultiPar() || opts == JustText)
621                 runparams.html_make_pars = false;
622         if (il.isPassThru())
623                 runparams.pass_thru = true;
624
625         xhtmlParagraphs(text_, buffer(), xs, runparams);
626
627         if (opts & WriteInnerTag)
628                 xs << html::EndTag(il.htmlinnertag());
629
630         if (opts & WriteOuterTag)
631                 xs << html::EndTag(il.htmltag());
632
633         return docstring();
634 }
635
636 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
637                         bool const post) const
638 {
639         OutputParams runparams = runparams_in;
640         runparams.local_font =
641                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
642         if (isPassThru())
643                 runparams.pass_thru = true;
644         if (post)
645                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().postcommandargs(), "post:");
646         else
647                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().latexargs());
648 }
649
650
651 void InsetText::cursorPos(BufferView const & bv,
652                 CursorSlice const & sl, bool boundary, int & x, int & y) const
653 {
654         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
655         y = bv.textMetrics(&text_).cursorY(sl, boundary);
656 }
657
658
659 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
660 {
661         clear();
662         Paragraph & first = paragraphs().front();
663         for (unsigned int i = 0; i < data.length(); ++i)
664                 first.insertChar(i, data[i], font, trackChanges);
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                 // we need float information even in note insets (#9760)
780                 tclass.counters().current_float(savecnt.current_float());
781                 tclass.counters().isSubfloat(savecnt.isSubfloat());
782                 buffer().updateBuffer(it2, utype);
783                 tclass.counters() = savecnt;
784         }
785 }
786
787
788 void InsetText::toString(odocstream & os) const
789 {
790         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
791 }
792
793
794 void InsetText::forOutliner(docstring & os, size_t const maxlen,
795                                                         bool const shorten) const
796 {
797         if (!getLayout().isInToc())
798                 return;
799         text().forOutliner(os, maxlen, shorten);
800 }
801
802
803 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
804                                                  UpdateType utype) const
805 {
806         DocIterator dit = cdit;
807         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
808         iterateForToc(dit, output_active, utype);
809 }
810
811
812 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
813                                                           UpdateType utype) const
814 {
815         DocIterator dit = cdit;
816         // This also ensures that any document has a table of contents
817         shared_ptr<Toc> toc = buffer().tocBackend().toc("tableofcontents");
818
819         BufferParams const & bufparams = buffer_->params();
820         int const min_toclevel = bufparams.documentClass().min_toclevel();
821         // we really should have done this before we got here, but it
822         // can't hurt too much to do it again
823         bool const doing_output = output_active && producesOutput();
824
825         // For each paragraph, traverse its insets and let them add
826         // their toc items
827         ParagraphList const & pars = paragraphs();
828         pit_type pend = paragraphs().size();
829         for (pit_type pit = 0; pit != pend; ++pit) {
830                 Paragraph const & par = pars[pit];
831                 dit.pit() = pit;
832                 // if we find an optarg, we'll save it for use later.
833                 InsetText const * arginset = 0;
834                 InsetList::const_iterator it  = par.insetList().begin();
835                 InsetList::const_iterator end = par.insetList().end();
836                 for (; it != end; ++it) {
837                         Inset & inset = *it->inset;
838                         dit.pos() = it->pos;
839                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
840                         inset.addToToc(dit, doing_output, utype);
841                         if (inset.lyxCode() == ARG_CODE)
842                                 arginset = inset.asInsetText();
843                 }
844                 // now the toc entry for the paragraph
845                 int const toclevel = text().getTocLevel(pit);
846                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
847                         // insert this into the table of contents
848                         docstring tocstring;
849                         int const length = (doing_output && utype == OutputUpdate) ?
850                                 INT_MAX : TOC_ENTRY_LENGTH;
851                         if (arginset) {
852                                 tocstring = par.labelString();
853                                 if (!tocstring.empty())
854                                         tocstring += ' ';
855                                 arginset->text().forOutliner(tocstring, length);
856                         } else
857                                 par.forOutliner(tocstring, length);
858                         dit.pos() = 0;
859                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
860                                                                   tocstring, doing_output, tocstring));
861                 }
862                 
863                 // And now the list of changes.
864                 par.addChangesToToc(dit, buffer(), doing_output);
865         }
866 }
867
868
869 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
870 {
871         if (buffer().isClean())
872                 return Inset::notifyCursorLeaves(old, cur);
873         
874         // find text inset in old cursor
875         Cursor insetCur = old;
876         int scriptSlice = insetCur.find(this);
877         // we can try to continue here. returning true means
878         // the cursor is "now" invalid. which it was.
879         LASSERT(scriptSlice != -1, return true);
880         insetCur.cutOff(scriptSlice);
881         LASSERT(&insetCur.inset() == this, return true);
882         
883         // update the old paragraph's words
884         insetCur.paragraph().updateWords();
885         
886         return Inset::notifyCursorLeaves(old, cur);
887 }
888
889
890 bool InsetText::completionSupported(Cursor const & cur) const
891 {
892         //LASSERT(&cur.bv().cursor().inset() == this, return false);
893         return text_.completionSupported(cur);
894 }
895
896
897 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
898 {
899         return completionSupported(cur);
900 }
901
902
903 bool InsetText::automaticInlineCompletion() const
904 {
905         return lyxrc.completion_inline_text;
906 }
907
908
909 bool InsetText::automaticPopupCompletion() const
910 {
911         return lyxrc.completion_popup_text;
912 }
913
914
915 bool InsetText::showCompletionCursor() const
916 {
917         return lyxrc.completion_cursor_text;
918 }
919
920
921 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
922 {
923         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
924 }
925
926
927 docstring InsetText::completionPrefix(Cursor const & cur) const
928 {
929         if (!completionSupported(cur))
930                 return docstring();
931         return text_.completionPrefix(cur);
932 }
933
934
935 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
936         bool finished)
937 {
938         if (!completionSupported(cur))
939                 return false;
940
941         return text_.insertCompletion(cur, s, finished);
942 }
943
944
945 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
946         Dimension & dim) const
947 {
948         TextMetrics const & tm = cur.bv().textMetrics(&text_);
949         tm.completionPosAndDim(cur, x, y, dim);
950 }
951
952
953 string InsetText::contextMenu(BufferView const &, int, int) const
954 {
955         string context_menu = contextMenuName();
956         if (context_menu != InsetText::contextMenuName())
957                 context_menu += ";" + InsetText::contextMenuName(); 
958         return context_menu;
959 }
960
961
962 string InsetText::contextMenuName() const
963 {
964         return "context-edit";
965 }
966
967
968 docstring InsetText::toolTipText(docstring prefix,
969                 size_t numlines, size_t len) const
970 {
971         size_t const max_length = numlines * len;
972         OutputParams rp(&buffer().params().encoding());
973         rp.for_tooltip = true;
974         odocstringstream oss;
975         oss << prefix;
976
977         ParagraphList::const_iterator beg = paragraphs().begin();
978         ParagraphList::const_iterator end = paragraphs().end();
979         ParagraphList::const_iterator it = beg;
980         bool ref_printed = false;
981         docstring str;
982
983         for (; it != end; ++it) {
984                 if (it != beg)
985                         oss << '\n';
986                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, max_length);
987                 str = oss.str();
988                 if (str.length() >= max_length)
989                         break;
990         }
991         return support::wrapParas(str, 4, len, numlines);
992 }
993
994
995 InsetCaption const * InsetText::getCaptionInset() const
996 {
997         ParagraphList::const_iterator pit = paragraphs().begin();
998         for (; pit != paragraphs().end(); ++pit) {
999                 InsetList::const_iterator it = pit->insetList().begin();
1000                 for (; it != pit->insetList().end(); ++it) {
1001                         Inset & inset = *it->inset;
1002                         if (inset.lyxCode() == CAPTION_CODE) {
1003                                 InsetCaption const * ins =
1004                                         static_cast<InsetCaption const *>(it->inset);
1005                                 return ins;
1006                         }
1007                 }
1008         }
1009         return 0;
1010 }
1011
1012
1013 docstring InsetText::getCaptionText(OutputParams const & runparams) const
1014 {
1015         InsetCaption const * ins = getCaptionInset();
1016         if (ins == 0)
1017                 return docstring();
1018
1019         odocstringstream ods;
1020         ins->getCaptionAsPlaintext(ods, runparams);
1021         return ods.str();
1022 }
1023
1024
1025 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
1026 {
1027         InsetCaption const * ins = getCaptionInset();
1028         if (ins == 0)
1029                 return docstring();
1030
1031         odocstringstream ods;
1032         XHTMLStream xs(ods);
1033         docstring def = ins->getCaptionAsHTML(xs, runparams);
1034         if (!def.empty())
1035                 // should already have been escaped
1036                 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
1037         return ods.str();
1038 }
1039
1040
1041 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1042 {
1043         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1044 }
1045
1046 } // namespace lyx