]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Fix drawing of collpsable insets
[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 "InsetList.h"
31 #include "Intl.h"
32 #include "Language.h"
33 #include "Layout.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "lyxfind.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_xhtml.h"
42 #include "OutputParams.h"
43 #include "output_plaintext.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Row.h"
48 #include "sgml.h"
49 #include "TexRow.h"
50 #include "texstream.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/bind.h"
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/RefChanger.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::dimensionHelper(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         int const w = tm.width() + TEXT_TO_INSET_OFFSET;
219         int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
220         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
221         int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
222         bool change_drawn = false;
223         if (drawFrame_ || pi.full_repaint) {
224                 // Change color of the frame in tracked changes, like for tabulars.
225                 // Only do so if the color is not custom. But do so even if RowPainter
226                 // handles the strike-through already.
227                 Color c;
228                 if (pi.change_.changed()
229                     // Originally, these are the colors with role Text, from role() in
230                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
231                     // types, and also maybe it need not match in the future.
232                     && (frameColor() == Color_foreground
233                         || frameColor() == Color_cursor
234                         || frameColor() == Color_preview
235                         || frameColor() == Color_tabularline
236                         || frameColor() == Color_previewframe)) {
237                         c = pi.change_.color();
238                         change_drawn = true;
239                 } else
240                         c = frameColor();
241                 if (drawFrame_)
242                         pi.pain.rectangle(xframe, yframe, w, h, c);
243         }
244         {
245                 Changer dummy = make_change(pi.background_color,
246                                             pi.backgroundColor(this, false));
247                 // The change tracking cue must not be inherited
248                 Changer dummy2 = make_change(pi.change_, Change());
249                 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
250         }
251         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
252                 // Do not draw the change tracking cue if already done by RowPainter and
253                 // do not draw the cue for INSERTED if the information is already in the
254                 // color of the frame
255                 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
256 }
257
258
259 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
260 {
261         pit_type const pit = front ? 0 : paragraphs().size() - 1;
262         pos_type pos = front ? 0 : paragraphs().back().size();
263
264         // if visual information is not to be ignored, move to extreme right/left
265         if (entry_from != ENTRY_DIRECTION_IGNORE) {
266                 Cursor temp_cur = cur;
267                 temp_cur.pit() = pit;
268                 temp_cur.pos() = pos;
269                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
270                 pos = temp_cur.pos();
271         }
272
273         cur.top().setPitPos(pit, pos);
274         cur.finishUndo();
275 }
276
277
278 Inset * InsetText::editXY(Cursor & cur, int x, int y)
279 {
280         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
281 }
282
283
284 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
285 {
286         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
287
288         // See bug #9042, for instance.
289         if (isPassThru()) {
290                 // Force any new text to latex_language FIXME: This
291                 // should only be necessary in constructor, but new
292                 // paragraphs that are created by pressing enter at
293                 // the start of an existing paragraph get the buffer
294                 // language and not latex_language, so we take this
295                 // brute force approach.
296                 cur.current_font.setLanguage(latex_language);
297                 cur.real_current_font.setLanguage(latex_language);
298         }
299
300         switch (cmd.action()) {
301         case LFUN_PASTE:
302         case LFUN_CLIPBOARD_PASTE:
303         case LFUN_SELECTION_PASTE:
304         case LFUN_PRIMARY_SELECTION_PASTE:
305                 text_.dispatch(cur, cmd);
306                 // If we we can only store plain text, we must reset all
307                 // attributes.
308                 // FIXME: Change only the pasted paragraphs
309                 fixParagraphsFont();
310                 break;
311
312         case LFUN_INSET_DISSOLVE: {
313                 bool const main_inset = text_.isMainText();
314                 bool const target_inset = cmd.argument().empty() 
315                         || cmd.getArg(0) == insetName(lyxCode());
316                 // cur.inset() is the tabular when this is a single cell (bug #9954)
317                 bool const one_cell = cur.inset().nargs() == 1;
318
319                 if (!main_inset && target_inset && one_cell) {
320                         // Text::dissolveInset assumes that the cursor
321                         // is inside the Inset.
322                         if (&cur.inset() != this)
323                                 cur.pushBackward(*this);
324                         cur.beginUndoGroup();
325                         text_.dispatch(cur, cmd);
326                         cur.endUndoGroup();
327                 } else
328                         cur.undispatched();
329                 break;
330         }
331
332         default:
333                 text_.dispatch(cur, cmd);
334         }
335         
336         if (!cur.result().dispatched())
337                 Inset::doDispatch(cur, cmd);
338 }
339
340
341 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
342         FuncStatus & status) const
343 {
344         switch (cmd.action()) {
345         case LFUN_INSET_DISSOLVE: {
346                 bool const main_inset = text_.isMainText();
347                 bool const target_inset = cmd.argument().empty() 
348                         || cmd.getArg(0) == insetName(lyxCode());
349                 // cur.inset() is the tabular when this is a single cell (bug #9954)
350                 bool const one_cell = cur.inset().nargs() == 1;
351
352                 if (target_inset)
353                         status.setEnabled(!main_inset && one_cell);
354                 return target_inset;
355         }
356
357         case LFUN_ARGUMENT_INSERT: {
358                 string const arg = cmd.getArg(0);
359                 if (arg.empty()) {
360                         status.setEnabled(false);
361                         return true;
362                 }
363                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
364                         return text_.getStatus(cur, cmd, status);
365
366                 Layout::LaTeXArgMap args = getLayout().args();
367                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
368                 if (lait != args.end()) {
369                         status.setEnabled(true);
370                         for (Paragraph const & par : paragraphs())
371                                 for (auto const & table : par.insetList())
372                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
373                                                 if (ins->name() == arg) {
374                                                         // we have this already
375                                                         status.setEnabled(false);
376                                                         return true;
377                                                 }
378                 } else
379                         status.setEnabled(false);
380                 return true;
381         }
382
383         default:
384                 // Dispatch only to text_ if the cursor is inside
385                 // the text_. It is not for context menus (bug 5797).
386                 bool ret = false;
387                 if (cur.text() == &text_)
388                         ret = text_.getStatus(cur, cmd, status);
389                 
390                 if (!ret)
391                         ret = Inset::getStatus(cur, cmd, status);
392                 return ret;
393         }
394 }
395
396
397 void InsetText::fixParagraphsFont()
398 {
399         Font font(inherit_font, buffer().params().language);
400         font.setLanguage(latex_language);
401         ParagraphList::iterator par = paragraphs().begin();
402         ParagraphList::iterator const end = paragraphs().end();
403         while (par != end) {
404                 if (par->isPassThru())
405                         par->resetFonts(font);
406                 if (!par->allowParagraphCustomization())
407                         par->params().clear();
408                 ++par;
409         }
410 }
411
412
413 void InsetText::setChange(Change const & change)
414 {
415         ParagraphList::iterator pit = paragraphs().begin();
416         ParagraphList::iterator end = paragraphs().end();
417         for (; pit != end; ++pit) {
418                 pit->setChange(change);
419         }
420 }
421
422
423 void InsetText::acceptChanges()
424 {
425         text_.acceptChanges();
426 }
427
428
429 void InsetText::rejectChanges()
430 {
431         text_.rejectChanges();
432 }
433
434
435 void InsetText::validate(LaTeXFeatures & features) const
436 {
437         features.useInsetLayout(getLayout());
438         for (Paragraph const & p : paragraphs())
439                 p.validate(features);
440 }
441
442
443 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
444 {
445         // This implements the standard way of handling the LaTeX
446         // output of a text inset, either a command or an
447         // environment. Standard collapsable insets should not
448         // redefine this, non-standard ones may call this.
449         InsetLayout const & il = getLayout();
450         if (il.forceOwnlines())
451                 os << breakln;
452         if (!il.latexname().empty()) {
453                 if (il.latextype() == InsetLayout::COMMAND) {
454                         // FIXME UNICODE
455                         // FIXME \protect should only be used for fragile
456                         //    commands, but we do not provide this information yet.
457                         if (runparams.moving_arg)
458                                 os << "\\protect";
459                         os << '\\' << from_utf8(il.latexname());
460                         if (!il.latexargs().empty())
461                                 getArgs(os, runparams);
462                         if (!il.latexparam().empty())
463                                 os << from_utf8(il.latexparam());
464                         os << '{';
465                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
466                         if (il.isDisplay())
467                                 os << breakln;
468                         else
469                                 os << safebreakln;
470                         if (runparams.lastid != -1)
471                                 os.texrow().start(runparams.lastid,
472                                                   runparams.lastpos);
473                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
474                         if (!il.latexargs().empty())
475                                 getArgs(os, runparams);
476                         if (!il.latexparam().empty())
477                                 os << from_utf8(il.latexparam());
478                         os << '\n';
479                 }
480         } else {
481                 if (!il.latexargs().empty())
482                         getArgs(os, runparams);
483                 if (!il.latexparam().empty())
484                         os << from_utf8(il.latexparam());
485         }
486
487         if (!il.leftdelim().empty())
488                 os << il.leftdelim();
489
490         OutputParams rp = runparams;
491         if (isPassThru())
492                 rp.pass_thru = true;
493         if (il.isNeedProtect())
494                 rp.moving_arg = true;
495         if (!il.passThruChars().empty())
496                 rp.pass_thru_chars += il.passThruChars();
497         rp.par_begin = 0;
498         rp.par_end = paragraphs().size();
499
500         // Output the contents of the inset
501         latexParagraphs(buffer(), text_, os, rp);
502         runparams.encoding = rp.encoding;
503
504         if (!il.rightdelim().empty())
505                 os << il.rightdelim();
506
507         if (!il.latexname().empty()) {
508                 if (il.latextype() == InsetLayout::COMMAND) {
509                         os << "}";
510                         if (!il.postcommandargs().empty())
511                                 getArgs(os, runparams, true);
512                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
513                         // A comment environment doesn't need a % before \n\end
514                         if (il.isDisplay() || runparams.inComment)
515                                 os << breakln;
516                         else
517                                 os << safebreakln;
518                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
519                         if (!il.isDisplay())
520                                 os.protectSpace(true);
521                 }
522         }
523         if (il.forceOwnlines())
524                 os << breakln;
525 }
526
527
528 int InsetText::plaintext(odocstringstream & os,
529         OutputParams const & runparams, size_t max_length) const
530 {
531         ParagraphList::const_iterator beg = paragraphs().begin();
532         ParagraphList::const_iterator end = paragraphs().end();
533         ParagraphList::const_iterator it = beg;
534         bool ref_printed = false;
535         int len = 0;
536         for (; it != end; ++it) {
537                 if (it != beg) {
538                         os << '\n';
539                         if (runparams.linelen > 0)
540                                 os << '\n';
541                 }
542                 odocstringstream oss;
543                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
544                 docstring const str = oss.str();
545                 os << str;
546                 // FIXME: len is not computed fully correctly; in principle,
547                 // we have to count the characters after the last '\n'
548                 len = str.size();
549                 if (os.str().size() >= max_length)
550                         break;
551         }
552
553         return len;
554 }
555
556
557 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
558 {
559         ParagraphList::const_iterator const beg = paragraphs().begin();
560
561         if (!undefined())
562                 sgml::openTag(os, getLayout().latexname(),
563                               beg->getID(buffer(), runparams) + getLayout().latexparam());
564
565         docbookParagraphs(text_, buffer(), os, runparams);
566
567         if (!undefined())
568                 sgml::closeTag(os, getLayout().latexname());
569
570         return 0;
571 }
572
573
574 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
575 {
576         return insetAsXHTML(xs, runparams, WriteEverything);
577 }
578
579
580 // FIXME XHTML
581 // There are cases where we may need to close open fonts and such
582 // and then re-open them when we are done. This would be the case, e.g.,
583 // if we were otherwise about to write:
584 //              <em>word <div class='foot'>footnote text.</div> emph</em>
585 // The problem isn't so much that the footnote text will get emphasized:
586 // we can handle that with CSS. The problem is that this is invalid XHTML.
587 // One solution would be to make the footnote <span>, but the problem is
588 // completely general, and so we'd have to make absolutely everything into
589 // span. What I think will work is to check if we're about to write "div" and,
590 // if so, try to close fonts, etc. 
591 // There are probably limits to how well we can do here, though, and we will
592 // have to rely upon users not putting footnotes inside noun-type insets.
593 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
594                                   XHTMLOptions opts) const
595 {
596         // we will always want to output all our paragraphs when we are
597         // called this way.
598         OutputParams runparams = rp;
599         runparams.par_begin = 0;
600         runparams.par_end = text().paragraphs().size();
601         
602         if (undefined()) {
603                 xs.startDivision(false);
604                 xhtmlParagraphs(text_, buffer(), xs, runparams);
605                 xs.endDivision();
606                 return docstring();
607         }
608
609         InsetLayout const & il = getLayout();
610         if (opts & WriteOuterTag)
611                 xs << html::StartTag(il.htmltag(), il.htmlattr());
612
613         if ((opts & WriteLabel) && !il.counter().empty()) {
614                 BufferParams const & bp = buffer().masterBuffer()->params();
615                 Counters & cntrs = bp.documentClass().counters();
616                 cntrs.step(il.counter(), OutputUpdate);
617                 // FIXME: translate to paragraph language
618                 if (!il.htmllabel().empty()) {
619                         docstring const lbl = 
620                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
621                         // FIXME is this check necessary?
622                         if (!lbl.empty()) {
623                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
624                                 xs << lbl;
625                                 xs << html::EndTag(il.htmllabeltag());
626                         }
627                 }
628         }
629
630         if (opts & WriteInnerTag)
631                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
632
633         // we will eventually lose information about the containing inset
634         if (!allowMultiPar() || opts == JustText)
635                 runparams.html_make_pars = false;
636         if (il.isPassThru())
637                 runparams.pass_thru = true;
638
639         xs.startDivision(false);
640         xhtmlParagraphs(text_, buffer(), xs, runparams);
641         xs.endDivision();
642
643         if (opts & WriteInnerTag)
644                 xs << html::EndTag(il.htmlinnertag());
645
646         if (opts & WriteOuterTag)
647                 xs << html::EndTag(il.htmltag());
648
649         return docstring();
650 }
651
652
653 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
654                         bool const post) const
655 {
656         OutputParams runparams = runparams_in;
657         runparams.local_font =
658                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
659         if (isPassThru())
660                 runparams.pass_thru = true;
661         if (post)
662                 latexArgInsetsForParent(paragraphs(), os, runparams,
663                                         getLayout().postcommandargs(), "post:");
664         else
665                 latexArgInsetsForParent(paragraphs(), os, runparams,
666                                         getLayout().latexargs());
667 }
668
669
670 void InsetText::cursorPos(BufferView const & bv,
671                 CursorSlice const & sl, bool boundary, int & x, int & y) const
672 {
673         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
674         y = bv.textMetrics(&text_).cursorY(sl, boundary);
675 }
676
677
678 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
679 {
680         clear();
681         Paragraph & first = paragraphs().front();
682         for (unsigned int i = 0; i < data.length(); ++i)
683                 first.insertChar(i, data[i], font, trackChanges);
684 }
685
686
687 void InsetText::setDrawFrame(bool flag)
688 {
689         drawFrame_ = flag;
690 }
691
692
693 ColorCode InsetText::frameColor() const
694 {
695         return frame_color_;
696 }
697
698
699 void InsetText::setFrameColor(ColorCode col)
700 {
701         frame_color_ = col;
702 }
703
704
705 void InsetText::appendParagraphs(ParagraphList & plist)
706 {
707         // There is little we can do here to keep track of changes.
708         // As of 2006/10/20, appendParagraphs is used exclusively by
709         // LyXTabular::setMultiColumn. In this context, the paragraph break
710         // is lost irreversibly and the appended text doesn't really change
711
712         ParagraphList & pl = paragraphs();
713
714         ParagraphList::iterator pit = plist.begin();
715         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
716         ++pit;
717         mergeParagraph(buffer().params(), pl,
718                        distance(pl.begin(), ins) - 1);
719
720         for_each(pit, plist.end(),
721                  bind(&ParagraphList::push_back, ref(pl), _1));
722 }
723
724
725 void InsetText::addPreview(DocIterator const & text_inset_pos,
726         PreviewLoader & loader) const
727 {
728         ParagraphList::const_iterator pit = paragraphs().begin();
729         ParagraphList::const_iterator pend = paragraphs().end();
730         int pidx = 0;
731
732         DocIterator inset_pos = text_inset_pos;
733         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
734
735         for (; pit != pend; ++pit, ++pidx) {
736                 InsetList::const_iterator it  = pit->insetList().begin();
737                 InsetList::const_iterator end = pit->insetList().end();
738                 inset_pos.pit() = pidx;
739                 for (; it != end; ++it) {
740                         inset_pos.pos() = it->pos;
741                         it->inset->addPreview(inset_pos, loader);
742                 }
743         }
744 }
745
746
747 ParagraphList const & InsetText::paragraphs() const
748 {
749         return text_.paragraphs();
750 }
751
752
753 ParagraphList & InsetText::paragraphs()
754 {
755         return text_.paragraphs();
756 }
757
758
759 bool InsetText::insetAllowed(InsetCode code) const
760 {
761         switch (code) {
762         // Arguments and (plain) quotes are also allowed in PassThru insets
763         case ARG_CODE:
764         case QUOTE_CODE:
765                 return true;
766         default:
767                 return !isPassThru();
768         }
769 }
770
771
772 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
773 {
774         ParIterator it2 = it;
775         it2.forwardPos();
776         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
777         if (producesOutput()) {
778                 InsetLayout const & il = getLayout();
779                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
780                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
781                 if (save_layouts) {
782                         // LYXERR0("Entering " << name());
783                         cnt.clearLastLayout();
784                         // FIXME cnt.saveLastCounter()?
785                 }
786                 buffer().updateBuffer(it2, utype);
787                 if (save_layouts) {
788                         // LYXERR0("Exiting " << name());
789                         cnt.restoreLastLayout();
790                         // FIXME cnt.restoreLastCounter()?
791                 }
792         } else {
793                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
794                 // Note that we do not need to call:
795                 //      tclass.counters().clearLastLayout()
796                 // since we are saving and restoring the existing counters, etc.
797                 Counters const savecnt = tclass.counters();
798                 tclass.counters().reset();
799                 // we need float information even in note insets (#9760)
800                 tclass.counters().current_float(savecnt.current_float());
801                 tclass.counters().isSubfloat(savecnt.isSubfloat());
802                 buffer().updateBuffer(it2, utype);
803                 tclass.counters() = savecnt;
804         }
805 }
806
807
808 void InsetText::toString(odocstream & os) const
809 {
810         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
811 }
812
813
814 void InsetText::forOutliner(docstring & os, size_t const maxlen,
815                                                         bool const shorten) const
816 {
817         if (!getLayout().isInToc())
818                 return;
819         text().forOutliner(os, maxlen, shorten);
820 }
821
822
823 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
824                                                  UpdateType utype, TocBackend & backend) const
825 {
826         DocIterator dit = cdit;
827         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
828         iterateForToc(dit, output_active, utype, backend);
829 }
830
831
832 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
833                                                           UpdateType utype, TocBackend & backend) const
834 {
835         DocIterator dit = cdit;
836         // This also ensures that any document has a table of contents
837         shared_ptr<Toc> toc = backend.toc("tableofcontents");
838
839         BufferParams const & bufparams = buffer_->params();
840         int const min_toclevel = bufparams.documentClass().min_toclevel();
841         // we really should have done this before we got here, but it
842         // can't hurt too much to do it again
843         bool const doing_output = output_active && producesOutput();
844
845         // For each paragraph,
846         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
847         //   paragraphs as needed.
848         // * Traverse its insets and let them add their toc items
849         // * Compute the main table of contents (this is hardcoded)
850         // * Add the list of changes
851         ParagraphList const & pars = paragraphs();
852         pit_type pend = paragraphs().size();
853         // Record pairs {start,end} of where a toc item was opened for a paragraph
854         // and where it must be closed
855         stack<pair<pit_type, pit_type>> addtotoc_stack;
856
857         for (pit_type pit = 0; pit != pend; ++pit) {
858                 Paragraph const & par = pars[pit];
859                 dit.pit() = pit;
860                 dit.pos() = 0;
861
862                 // Custom AddToToc in paragraph layouts (i.e. theorems)
863                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
864                         pit_type end =
865                                 openAddToTocForParagraph(pit, dit, output_active, backend);
866                         addtotoc_stack.push({pit, end});
867                 }
868
869                 // if we find an optarg, we'll save it for use later.
870                 InsetArgument const * arginset = nullptr;
871                 for (auto const & table : par.insetList()) {
872                         dit.pos() = table.pos;
873                         table.inset->addToToc(dit, doing_output, utype, backend);
874                         if (InsetArgument const * x = table.inset->asInsetArgument())
875                                 arginset = x;
876                 }
877
878                 // End custom AddToToc in paragraph layouts
879                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
880                         // execute the closing function
881                         closeAddToTocForParagraph(addtotoc_stack.top().first,
882                                                   addtotoc_stack.top().second, backend);
883                         addtotoc_stack.pop();
884                 }
885
886                 // now the toc entry for the paragraph in the main table of contents
887                 int const toclevel = text().getTocLevel(pit);
888                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
889                         // insert this into the table of contents
890                         docstring tocstring;
891                         int const length = (doing_output && utype == OutputUpdate) ?
892                                 INT_MAX : TOC_ENTRY_LENGTH;
893                         if (arginset) {
894                                 tocstring = par.labelString();
895                                 if (!tocstring.empty())
896                                         tocstring += ' ';
897                                 arginset->text().forOutliner(tocstring, length);
898                         } else
899                                 par.forOutliner(tocstring, length);
900                         dit.pos() = 0;
901                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
902                                                tocstring, doing_output));
903                 }
904
905                 // And now the list of changes.
906                 par.addChangesToToc(dit, buffer(), doing_output, backend);
907         }
908 }
909
910
911 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
912                                              DocIterator const & dit,
913                                              bool output_active,
914                                              TocBackend & backend) const
915 {
916         Paragraph const & par = paragraphs()[pit];
917         TocBuilder & b = backend.builder(par.layout().tocType());
918         docstring const label = par.labelString();
919         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
920         return text().lastInSequence(pit);
921 }
922
923
924 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
925                                           TocBackend & backend) const
926 {
927         Paragraph const & par = paragraphs()[start];
928         TocBuilder & b = backend.builder(par.layout().tocType());
929         if (par.layout().isTocCaption()) {
930                 docstring str;
931                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
932                 b.argumentItem(str);
933         }
934         b.pop();
935 }
936
937
938 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
939 {
940         if (buffer().isClean())
941                 return Inset::notifyCursorLeaves(old, cur);
942         
943         // find text inset in old cursor
944         Cursor insetCur = old;
945         int scriptSlice = insetCur.find(this);
946         // we can try to continue here. returning true means
947         // the cursor is "now" invalid. which it was.
948         LASSERT(scriptSlice != -1, return true);
949         insetCur.cutOff(scriptSlice);
950         LASSERT(&insetCur.inset() == this, return true);
951         
952         // update the old paragraph's words
953         insetCur.paragraph().updateWords();
954         
955         return Inset::notifyCursorLeaves(old, cur);
956 }
957
958
959 bool InsetText::completionSupported(Cursor const & cur) const
960 {
961         //LASSERT(&cur.bv().cursor().inset() == this, return false);
962         return text_.completionSupported(cur);
963 }
964
965
966 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
967 {
968         return completionSupported(cur);
969 }
970
971
972 bool InsetText::automaticInlineCompletion() const
973 {
974         return lyxrc.completion_inline_text;
975 }
976
977
978 bool InsetText::automaticPopupCompletion() const
979 {
980         return lyxrc.completion_popup_text;
981 }
982
983
984 bool InsetText::showCompletionCursor() const
985 {
986         return lyxrc.completion_cursor_text;
987 }
988
989
990 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
991 {
992         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
993 }
994
995
996 docstring InsetText::completionPrefix(Cursor const & cur) const
997 {
998         if (!completionSupported(cur))
999                 return docstring();
1000         return text_.completionPrefix(cur);
1001 }
1002
1003
1004 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1005         bool finished)
1006 {
1007         if (!completionSupported(cur))
1008                 return false;
1009
1010         return text_.insertCompletion(cur, s, finished);
1011 }
1012
1013
1014 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1015         Dimension & dim) const
1016 {
1017         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1018         tm.completionPosAndDim(cur, x, y, dim);
1019 }
1020
1021
1022 string InsetText::contextMenu(BufferView const &, int, int) const
1023 {
1024         string context_menu = contextMenuName();
1025         if (context_menu != InsetText::contextMenuName())
1026                 context_menu += ";" + InsetText::contextMenuName(); 
1027         return context_menu;
1028 }
1029
1030
1031 string InsetText::contextMenuName() const
1032 {
1033         return "context-edit";
1034 }
1035
1036
1037 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1038 {
1039         OutputParams rp(&buffer().params().encoding());
1040         rp.for_tooltip = true;
1041         odocstringstream oss;
1042         oss << prefix;
1043
1044         ParagraphList::const_iterator beg = paragraphs().begin();
1045         ParagraphList::const_iterator end = paragraphs().end();
1046         ParagraphList::const_iterator it = beg;
1047         bool ref_printed = false;
1048
1049         for (; it != end; ++it) {
1050                 if (it != beg)
1051                         oss << '\n';
1052                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1053                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1054                         break;
1055         }
1056         docstring str = oss.str();
1057         support::truncateWithEllipsis(str, len);
1058         return str;
1059 }
1060
1061
1062 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1063 {
1064         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1065 }
1066
1067 } // namespace lyx