]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Fixup b321bb1a: set changebar when inset contains changes
[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), drawFrame_(in.drawFrame_), frame_color_(in.frame_color_),
90           text_(this, in.text_)
91 {
92 }
93
94
95 void InsetText::setBuffer(Buffer & buf)
96 {
97         ParagraphList::iterator end = paragraphs().end();
98         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
99                 it->setInsetBuffers(buf);
100         Inset::setBuffer(buf);
101 }
102
103
104 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
105 {
106         text_.setMacrocontextPosition(pos);
107
108         ParagraphList::const_iterator pit = paragraphs().begin();
109         ParagraphList::const_iterator pend = paragraphs().end();
110         for (; pit != pend; ++pit) {
111                 InsetList::const_iterator iit = pit->insetList().begin();
112                 InsetList::const_iterator end = pit->insetList().end();
113                 for (; iit != end; ++iit) {
114                         if (InsetText * txt = iit->inset->asInsetText()) {
115                                 DocIterator ppos(pos);
116                                 ppos.push_back(CursorSlice(*txt));
117                                 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
118                         }
119                 }
120         }
121 }
122
123
124 void InsetText::clear()
125 {
126         ParagraphList & pars = paragraphs();
127         LBUFERR(!pars.empty());
128
129         // This is a gross hack...
130         Layout const & old_layout = pars.begin()->layout();
131
132         pars.clear();
133         pars.push_back(Paragraph());
134         pars.begin()->setInsetOwner(this);
135         pars.begin()->setLayout(old_layout);
136 }
137
138
139 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
140 {
141         TextMetrics const & tm = bv.textMetrics(&text_);
142         Dimension dim = tm.dim();
143         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
144         dim.des += TEXT_TO_INSET_OFFSET;
145         dim.asc += TEXT_TO_INSET_OFFSET;
146         return dim;
147 }
148
149
150 void InsetText::write(ostream & os) const
151 {
152         os << "Text\n";
153         text_.write(os);
154 }
155
156
157 void InsetText::read(Lexer & lex)
158 {
159         clear();
160
161         // delete the initial paragraph
162         Paragraph oldpar = *paragraphs().begin();
163         paragraphs().clear();
164         ErrorList errorList;
165         lex.setContext("InsetText::read");
166         bool res = text_.read(lex, errorList, this);
167
168         if (!res)
169                 lex.printError("Missing \\end_inset at this point. ");
170
171         // sanity check
172         // ensure we have at least one paragraph.
173         if (paragraphs().empty())
174                 paragraphs().push_back(oldpar);
175         // Force default font, if so requested
176         // This avoids paragraphs in buffer language that would have a
177         // foreign language after a document language change, and it ensures
178         // that all new text in ERT and similar gets the "latex" language,
179         // since new text inherits the language from the last position of the
180         // existing text.  As a side effect this makes us also robust against
181         // bugs in LyX that might lead to font changes in ERT in .lyx files.
182         fixParagraphsFont();
183 }
184
185
186 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
187 {
188         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
189
190         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
191
192         // Hand font through to contained lyxtext:
193         tm.font_.fontInfo() = mi.base.font;
194         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
195
196         // This can happen when a layout has a left and right margin,
197         // and the view is made very narrow. We can't do better than
198         // to draw it partly out of view (bug 5890).
199         if (mi.base.textwidth < 1)
200                 mi.base.textwidth = 1;
201
202         if (hasFixedWidth())
203                 tm.metrics(mi, dim, mi.base.textwidth);
204         else
205                 tm.metrics(mi, dim);
206         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
207         dim.asc += TEXT_TO_INSET_OFFSET;
208         dim.des += TEXT_TO_INSET_OFFSET;
209         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
210 }
211
212
213 void InsetText::draw(PainterInfo & pi, int x, int y) const
214 {
215         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
216
217         int const w = tm.width() + TEXT_TO_INSET_OFFSET;
218         int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
219         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
220         int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
221         bool change_drawn = false;
222         if (pi.full_repaint)
223                         pi.pain.fillRectangle(xframe, yframe, w, h,
224                                 pi.backgroundColor(this));
225
226         {
227                 Changer dummy = make_change(pi.background_color,
228                                             pi.backgroundColor(this, false));
229                 // The change tracking cue must not be inherited
230                 Changer dummy2 = make_change(pi.change_, Change());
231                 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
232         }
233
234         if (drawFrame_) {
235                 // Change color of the frame in tracked changes, like for tabulars.
236                 // Only do so if the color is not custom. But do so even if RowPainter
237                 // handles the strike-through already.
238                 Color c;
239                 if (pi.change_.changed()
240                     // Originally, these are the colors with role Text, from role() in
241                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
242                     // types, and also maybe it need not match in the future.
243                     && (frameColor() == Color_foreground
244                         || frameColor() == Color_cursor
245                         || frameColor() == Color_preview
246                         || frameColor() == Color_tabularline
247                         || frameColor() == Color_previewframe)) {
248                         c = pi.change_.color();
249                         change_drawn = true;
250                 } else
251                         c = frameColor();
252                 pi.pain.rectangle(xframe, yframe, w, h, c);
253         }
254
255         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
256                 // Do not draw the change tracking cue if already done by RowPainter and
257                 // do not draw the cue for INSERTED if the information is already in the
258                 // color of the frame
259                 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
260 }
261
262
263 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
264 {
265         pit_type const pit = front ? 0 : paragraphs().size() - 1;
266         pos_type pos = front ? 0 : paragraphs().back().size();
267
268         // if visual information is not to be ignored, move to extreme right/left
269         if (entry_from != ENTRY_DIRECTION_IGNORE) {
270                 Cursor temp_cur = cur;
271                 temp_cur.pit() = pit;
272                 temp_cur.pos() = pos;
273                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
274                 pos = temp_cur.pos();
275         }
276
277         cur.top().setPitPos(pit, pos);
278         cur.finishUndo();
279 }
280
281
282 Inset * InsetText::editXY(Cursor & cur, int x, int y)
283 {
284         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
285 }
286
287
288 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
289 {
290         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
291
292         // See bug #9042, for instance.
293         if (isPassThru()) {
294                 // Force any new text to latex_language FIXME: This
295                 // should only be necessary in constructor, but new
296                 // paragraphs that are created by pressing enter at
297                 // the start of an existing paragraph get the buffer
298                 // language and not latex_language, so we take this
299                 // brute force approach.
300                 cur.current_font.setLanguage(latex_language);
301                 cur.real_current_font.setLanguage(latex_language);
302         }
303
304         switch (cmd.action()) {
305         case LFUN_PASTE:
306         case LFUN_CLIPBOARD_PASTE:
307         case LFUN_SELECTION_PASTE:
308         case LFUN_PRIMARY_SELECTION_PASTE:
309                 text_.dispatch(cur, cmd);
310                 // If we we can only store plain text, we must reset all
311                 // attributes.
312                 // FIXME: Change only the pasted paragraphs
313                 fixParagraphsFont();
314                 break;
315
316         case LFUN_INSET_DISSOLVE: {
317                 bool const main_inset = text_.isMainText();
318                 bool const target_inset = cmd.argument().empty()
319                         || cmd.getArg(0) == insetName(lyxCode());
320
321                 if (!main_inset && target_inset) {
322                         // Text::dissolveInset assumes that the cursor
323                         // is inside the Inset.
324                         if (&cur.inset() != this)
325                                 cur.pushBackward(*this);
326                         cur.beginUndoGroup();
327                         text_.dispatch(cur, cmd);
328                         cur.endUndoGroup();
329                 } else
330                         cur.undispatched();
331                 break;
332         }
333
334         default:
335                 text_.dispatch(cur, cmd);
336         }
337
338         if (!cur.result().dispatched())
339                 Inset::doDispatch(cur, cmd);
340 }
341
342
343 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
344         FuncStatus & status) const
345 {
346         switch (cmd.action()) {
347         case LFUN_INSET_DISSOLVE: {
348                 bool const main_inset = text_.isMainText();
349                 bool const target_inset = cmd.argument().empty()
350                         || cmd.getArg(0) == insetName(lyxCode());
351
352                 if (target_inset)
353                         status.setEnabled(!main_inset);
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 bool InsetText::isChanged() const
414 {
415         ParagraphList::const_iterator pit = paragraphs().begin();
416         ParagraphList::const_iterator end = paragraphs().end();
417         for (; pit != end; ++pit) {
418                 if (pit->isChanged())
419                         return true;
420         }
421         return false;
422 }
423
424
425 void InsetText::setChange(Change const & change)
426 {
427         ParagraphList::iterator pit = paragraphs().begin();
428         ParagraphList::iterator end = paragraphs().end();
429         for (; pit != end; ++pit) {
430                 pit->setChange(change);
431         }
432 }
433
434
435 void InsetText::acceptChanges()
436 {
437         text_.acceptChanges();
438 }
439
440
441 void InsetText::rejectChanges()
442 {
443         text_.rejectChanges();
444 }
445
446
447 void InsetText::validate(LaTeXFeatures & features) const
448 {
449         features.useInsetLayout(getLayout());
450         for (Paragraph const & p : paragraphs())
451                 p.validate(features);
452 }
453
454
455 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
456 {
457         // This implements the standard way of handling the LaTeX
458         // output of a text inset, either a command or an
459         // environment. Standard collapsible insets should not
460         // redefine this, non-standard ones may call this.
461         InsetLayout const & il = getLayout();
462         if (il.forceOwnlines())
463                 os << breakln;
464         bool needendgroup = false;
465         if (!il.latexname().empty()) {
466                 if (il.latextype() == InsetLayout::COMMAND) {
467                         // FIXME UNICODE
468                         // FIXME \protect should only be used for fragile
469                         //    commands, but we do not provide this information yet.
470                         if (hasCProtectContent(runparams.moving_arg)) {
471                                 if (contains(runparams.active_chars, '^')) {
472                                         // cprotect relies on ^ being on catcode 7
473                                         os << "\\begingroup\\catcode`\\^=7";
474                                         needendgroup = true;
475                                 }
476                                 os << "\\cprotect";
477                         } else if (runparams.moving_arg)
478                                 os << "\\protect";
479                         os << '\\' << from_utf8(il.latexname());
480                         if (!il.latexargs().empty())
481                                 getArgs(os, runparams);
482                         if (!il.latexparam().empty())
483                                 os << from_utf8(il.latexparam());
484                         os << '{';
485                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
486                         if (il.isDisplay())
487                                 os << breakln;
488                         else
489                                 os << safebreakln;
490                         if (runparams.lastid != -1)
491                                 os.texrow().start(runparams.lastid,
492                                                   runparams.lastpos);
493                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
494                         if (!il.latexargs().empty())
495                                 getArgs(os, runparams);
496                         if (!il.latexparam().empty())
497                                 os << from_utf8(il.latexparam());
498                         os << '\n';
499                 }
500         } else {
501                 if (!il.latexargs().empty())
502                         getArgs(os, runparams);
503                 if (!il.latexparam().empty())
504                         os << from_utf8(il.latexparam());
505         }
506
507         if (!il.leftdelim().empty())
508                 os << il.leftdelim();
509
510         OutputParams rp = runparams;
511         if (isPassThru())
512                 rp.pass_thru = true;
513         if (il.isNeedProtect())
514                 rp.moving_arg = true;
515         if (il.isNeedMBoxProtect())
516                 ++rp.inulemcmd;
517         if (!il.passThruChars().empty())
518                 rp.pass_thru_chars += il.passThruChars();
519         if (!il.newlineCmd().empty())
520                 rp.newlinecmd = il.newlineCmd();
521         rp.par_begin = 0;
522         rp.par_end = paragraphs().size();
523
524         // Output the contents of the inset
525         latexParagraphs(buffer(), text_, os, rp);
526         runparams.encoding = rp.encoding;
527         // Pass the post_macros upstream
528         runparams.post_macro = rp.post_macro;
529
530         if (!il.rightdelim().empty())
531                 os << il.rightdelim();
532
533         if (!il.latexname().empty()) {
534                 if (il.latextype() == InsetLayout::COMMAND) {
535                         os << "}";
536                         if (!il.postcommandargs().empty())
537                                 getArgs(os, runparams, true);
538                         if (needendgroup)
539                                 os << "\\endgroup";
540                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
541                         // A comment environment doesn't need a % before \n\end
542                         if (il.isDisplay() || runparams.inComment)
543                                 os << breakln;
544                         else
545                                 os << safebreakln;
546                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
547                         if (!il.isDisplay())
548                                 os.protectSpace(true);
549                 }
550         }
551         if (il.forceOwnlines())
552                 os << breakln;
553 }
554
555
556 int InsetText::plaintext(odocstringstream & os,
557         OutputParams const & runparams, size_t max_length) const
558 {
559         ParagraphList::const_iterator beg = paragraphs().begin();
560         ParagraphList::const_iterator end = paragraphs().end();
561         ParagraphList::const_iterator it = beg;
562         bool ref_printed = false;
563         int len = 0;
564         for (; it != end; ++it) {
565                 if (it != beg) {
566                         os << '\n';
567                         if (runparams.linelen > 0)
568                                 os << '\n';
569                 }
570                 odocstringstream oss;
571                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
572                 docstring const str = oss.str();
573                 os << str;
574                 // FIXME: len is not computed fully correctly; in principle,
575                 // we have to count the characters after the last '\n'
576                 len = str.size();
577                 if (os.str().size() >= max_length)
578                         break;
579         }
580
581         return len;
582 }
583
584
585 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
586 {
587         ParagraphList::const_iterator const beg = paragraphs().begin();
588
589         if (!undefined())
590                 sgml::openTag(os, getLayout().latexname(),
591                               beg->getID(buffer(), runparams) + getLayout().latexparam());
592
593         docbookParagraphs(text_, buffer(), os, runparams);
594
595         if (!undefined())
596                 sgml::closeTag(os, getLayout().latexname());
597
598         return 0;
599 }
600
601
602 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
603 {
604         return insetAsXHTML(xs, runparams, WriteEverything);
605 }
606
607
608 // FIXME XHTML
609 // There are cases where we may need to close open fonts and such
610 // and then re-open them when we are done. This would be the case, e.g.,
611 // if we were otherwise about to write:
612 //              <em>word <div class='foot'>footnote text.</div> emph</em>
613 // The problem isn't so much that the footnote text will get emphasized:
614 // we can handle that with CSS. The problem is that this is invalid XHTML.
615 // One solution would be to make the footnote <span>, but the problem is
616 // completely general, and so we'd have to make absolutely everything into
617 // span. What I think will work is to check if we're about to write "div" and,
618 // if so, try to close fonts, etc.
619 // There are probably limits to how well we can do here, though, and we will
620 // have to rely upon users not putting footnotes inside noun-type insets.
621 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
622                                   XHTMLOptions opts) const
623 {
624         // we will always want to output all our paragraphs when we are
625         // called this way.
626         OutputParams runparams = rp;
627         runparams.par_begin = 0;
628         runparams.par_end = text().paragraphs().size();
629
630         if (undefined()) {
631                 xs.startDivision(false);
632                 xhtmlParagraphs(text_, buffer(), xs, runparams);
633                 xs.endDivision();
634                 return docstring();
635         }
636
637         InsetLayout const & il = getLayout();
638         if (opts & WriteOuterTag)
639                 xs << html::StartTag(il.htmltag(), il.htmlattr());
640
641         if ((opts & WriteLabel) && !il.counter().empty()) {
642                 BufferParams const & bp = buffer().masterBuffer()->params();
643                 Counters & cntrs = bp.documentClass().counters();
644                 cntrs.step(il.counter(), OutputUpdate);
645                 // FIXME: translate to paragraph language
646                 if (!il.htmllabel().empty()) {
647                         docstring const lbl =
648                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
649                         // FIXME is this check necessary?
650                         if (!lbl.empty()) {
651                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
652                                 xs << lbl;
653                                 xs << html::EndTag(il.htmllabeltag());
654                         }
655                 }
656         }
657
658         if (opts & WriteInnerTag)
659                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
660
661         // we will eventually lose information about the containing inset
662         if (!allowMultiPar() || opts == JustText)
663                 runparams.html_make_pars = false;
664         if (il.isPassThru())
665                 runparams.pass_thru = true;
666
667         xs.startDivision(false);
668         xhtmlParagraphs(text_, buffer(), xs, runparams);
669         xs.endDivision();
670
671         if (opts & WriteInnerTag)
672                 xs << html::EndTag(il.htmlinnertag());
673
674         if (opts & WriteOuterTag)
675                 xs << html::EndTag(il.htmltag());
676
677         return docstring();
678 }
679
680
681 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
682                         bool const post) const
683 {
684         OutputParams runparams = runparams_in;
685         runparams.local_font =
686                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
687         if (isPassThru())
688                 runparams.pass_thru = true;
689         if (post)
690                 latexArgInsetsForParent(paragraphs(), os, runparams,
691                                         getLayout().postcommandargs(), "post:");
692         else
693                 latexArgInsetsForParent(paragraphs(), os, runparams,
694                                         getLayout().latexargs());
695 }
696
697
698 void InsetText::cursorPos(BufferView const & bv,
699                 CursorSlice const & sl, bool boundary, int & x, int & y) const
700 {
701         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
702         y = bv.textMetrics(&text_).cursorY(sl, boundary);
703 }
704
705
706 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
707 {
708         clear();
709         Paragraph & first = paragraphs().front();
710         for (unsigned int i = 0; i < data.length(); ++i)
711                 first.insertChar(i, data[i], font, trackChanges);
712 }
713
714
715 void InsetText::setDrawFrame(bool flag)
716 {
717         drawFrame_ = flag;
718 }
719
720
721 ColorCode InsetText::frameColor() const
722 {
723         return frame_color_;
724 }
725
726
727 void InsetText::setFrameColor(ColorCode col)
728 {
729         frame_color_ = col;
730 }
731
732
733 void InsetText::appendParagraphs(ParagraphList & plist)
734 {
735         // There is little we can do here to keep track of changes.
736         // As of 2006/10/20, appendParagraphs is used exclusively by
737         // LyXTabular::setMultiColumn. In this context, the paragraph break
738         // is lost irreversibly and the appended text doesn't really change
739
740         ParagraphList & pl = paragraphs();
741
742         ParagraphList::iterator pit = plist.begin();
743         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
744         ++pit;
745         mergeParagraph(buffer().params(), pl,
746                        distance(pl.begin(), ins) - 1);
747
748         for_each(pit, plist.end(),
749                  bind(&ParagraphList::push_back, ref(pl), _1));
750 }
751
752
753 void InsetText::addPreview(DocIterator const & text_inset_pos,
754         PreviewLoader & loader) const
755 {
756         ParagraphList::const_iterator pit = paragraphs().begin();
757         ParagraphList::const_iterator pend = paragraphs().end();
758         int pidx = 0;
759
760         DocIterator inset_pos = text_inset_pos;
761         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
762
763         for (; pit != pend; ++pit, ++pidx) {
764                 InsetList::const_iterator it  = pit->insetList().begin();
765                 InsetList::const_iterator end = pit->insetList().end();
766                 inset_pos.pit() = pidx;
767                 for (; it != end; ++it) {
768                         inset_pos.pos() = it->pos;
769                         it->inset->addPreview(inset_pos, loader);
770                 }
771         }
772 }
773
774
775 ParagraphList const & InsetText::paragraphs() const
776 {
777         return text_.paragraphs();
778 }
779
780
781 ParagraphList & InsetText::paragraphs()
782 {
783         return text_.paragraphs();
784 }
785
786
787 bool InsetText::hasCProtectContent(bool fragile) const
788 {
789         fragile |= getLayout().isNeedProtect();
790         ParagraphList const & pars = paragraphs();
791         pit_type pend = pit_type(paragraphs().size());
792         for (pit_type pit = 0; pit != pend; ++pit) {
793                 Paragraph const & par = pars[size_type(pit)];
794                 if (par.needsCProtection(fragile))
795                         return true;
796         }
797         return false;
798 }
799
800
801 bool InsetText::insetAllowed(InsetCode code) const
802 {
803         switch (code) {
804         // Arguments and (plain) quotes are also allowed in PassThru insets
805         case ARG_CODE:
806         case QUOTE_CODE:
807                 return true;
808         default:
809                 return !isPassThru();
810         }
811 }
812
813
814 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
815 {
816         ParIterator it2 = it;
817         it2.forwardPos();
818         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
819         if (producesOutput()) {
820                 InsetLayout const & il = getLayout();
821                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
822                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
823                 if (save_layouts) {
824                         // LYXERR0("Entering " << name());
825                         cnt.clearLastLayout();
826                         // FIXME cnt.saveLastCounter()?
827                 }
828                 buffer().updateBuffer(it2, utype);
829                 if (save_layouts) {
830                         // LYXERR0("Exiting " << name());
831                         cnt.restoreLastLayout();
832                         // FIXME cnt.restoreLastCounter()?
833                 }
834         } else {
835                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
836                 // Note that we do not need to call:
837                 //      tclass.counters().clearLastLayout()
838                 // since we are saving and restoring the existing counters, etc.
839                 Counters savecnt = tclass.counters();
840                 tclass.counters().reset();
841                 // we need float information even in note insets (#9760)
842                 tclass.counters().current_float(savecnt.current_float());
843                 tclass.counters().isSubfloat(savecnt.isSubfloat());
844                 buffer().updateBuffer(it2, utype);
845                 tclass.counters() = move(savecnt);
846         }
847 }
848
849
850 void InsetText::toString(odocstream & os) const
851 {
852         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
853 }
854
855
856 void InsetText::forOutliner(docstring & os, size_t const maxlen,
857                                                         bool const shorten) const
858 {
859         if (!getLayout().isInToc())
860                 return;
861         text().forOutliner(os, maxlen, shorten);
862 }
863
864
865 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
866                                                  UpdateType utype, TocBackend & backend) const
867 {
868         DocIterator dit = cdit;
869         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
870         iterateForToc(dit, output_active, utype, backend);
871 }
872
873
874 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
875                                                           UpdateType utype, TocBackend & backend) const
876 {
877         DocIterator dit = cdit;
878         // This also ensures that any document has a table of contents
879         shared_ptr<Toc> toc = backend.toc("tableofcontents");
880
881         BufferParams const & bufparams = buffer_->params();
882         int const min_toclevel = bufparams.documentClass().min_toclevel();
883         // we really should have done this before we got here, but it
884         // can't hurt too much to do it again
885         bool const doing_output = output_active && producesOutput();
886
887         // For each paragraph,
888         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
889         //   paragraphs as needed.
890         // * Traverse its insets and let them add their toc items
891         // * Compute the main table of contents (this is hardcoded)
892         // * Add the list of changes
893         ParagraphList const & pars = paragraphs();
894         pit_type pend = paragraphs().size();
895         // Record pairs {start,end} of where a toc item was opened for a paragraph
896         // and where it must be closed
897         stack<pair<pit_type, pit_type>> addtotoc_stack;
898
899         for (pit_type pit = 0; pit != pend; ++pit) {
900                 Paragraph const & par = pars[pit];
901                 dit.pit() = pit;
902                 dit.pos() = 0;
903
904                 // Custom AddToToc in paragraph layouts (i.e. theorems)
905                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
906                         pit_type end =
907                                 openAddToTocForParagraph(pit, dit, output_active, backend);
908                         addtotoc_stack.push({pit, end});
909                 }
910
911                 // If we find an InsetArgument that is supposed to provide the TOC caption,
912                 // we'll save it for use later.
913                 InsetArgument const * arginset = nullptr;
914                 for (auto const & table : par.insetList()) {
915                         dit.pos() = table.pos;
916                         table.inset->addToToc(dit, doing_output, utype, backend);
917                         if (InsetArgument const * x = table.inset->asInsetArgument())
918                                 if (x->isTocCaption())
919                                         arginset = x;
920                 }
921
922                 // End custom AddToToc in paragraph layouts
923                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
924                         // execute the closing function
925                         closeAddToTocForParagraph(addtotoc_stack.top().first,
926                                                   addtotoc_stack.top().second, backend);
927                         addtotoc_stack.pop();
928                 }
929
930                 // now the toc entry for the paragraph in the main table of contents
931                 int const toclevel = text().getTocLevel(pit);
932                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
933                         // insert this into the table of contents
934                         docstring tocstring;
935                         int const length = (doing_output && utype == OutputUpdate) ?
936                                 INT_MAX : TOC_ENTRY_LENGTH;
937                         if (arginset) {
938                                 tocstring = par.labelString();
939                                 if (!tocstring.empty())
940                                         tocstring += ' ';
941                                 arginset->text().forOutliner(tocstring, length);
942                         } else
943                                 par.forOutliner(tocstring, length);
944                         dit.pos() = 0;
945                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
946                                                tocstring, doing_output));
947                 }
948
949                 // And now the list of changes.
950                 par.addChangesToToc(dit, buffer(), doing_output, backend);
951         }
952 }
953
954
955 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
956                                              DocIterator const & dit,
957                                              bool output_active,
958                                              TocBackend & backend) const
959 {
960         Paragraph const & par = paragraphs()[pit];
961         TocBuilder & b = backend.builder(par.layout().tocType());
962         docstring const label = par.labelString();
963         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
964         return text().lastInSequence(pit);
965 }
966
967
968 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
969                                           TocBackend & backend) const
970 {
971         Paragraph const & par = paragraphs()[start];
972         TocBuilder & b = backend.builder(par.layout().tocType());
973         if (par.layout().isTocCaption()) {
974                 docstring str;
975                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
976                 b.argumentItem(str);
977         }
978         b.pop();
979 }
980
981
982 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
983 {
984         if (buffer().isClean())
985                 return Inset::notifyCursorLeaves(old, cur);
986
987         // find text inset in old cursor
988         Cursor insetCur = old;
989         int scriptSlice = insetCur.find(this);
990         // we can try to continue here. returning true means
991         // the cursor is "now" invalid. which it was.
992         LASSERT(scriptSlice != -1, return true);
993         insetCur.cutOff(scriptSlice);
994         LASSERT(&insetCur.inset() == this, return true);
995
996         // update the old paragraph's words
997         insetCur.paragraph().updateWords();
998
999         return Inset::notifyCursorLeaves(old, cur);
1000 }
1001
1002
1003 bool InsetText::completionSupported(Cursor const & cur) const
1004 {
1005         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1006         return text_.completionSupported(cur);
1007 }
1008
1009
1010 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1011 {
1012         return completionSupported(cur);
1013 }
1014
1015
1016 bool InsetText::automaticInlineCompletion() const
1017 {
1018         return lyxrc.completion_inline_text;
1019 }
1020
1021
1022 bool InsetText::automaticPopupCompletion() const
1023 {
1024         return lyxrc.completion_popup_text;
1025 }
1026
1027
1028 bool InsetText::showCompletionCursor() const
1029 {
1030         return lyxrc.completion_cursor_text;
1031 }
1032
1033
1034 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1035 {
1036         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1037 }
1038
1039
1040 docstring InsetText::completionPrefix(Cursor const & cur) const
1041 {
1042         if (!completionSupported(cur))
1043                 return docstring();
1044         return text_.completionPrefix(cur);
1045 }
1046
1047
1048 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1049         bool finished)
1050 {
1051         if (!completionSupported(cur))
1052                 return false;
1053
1054         return text_.insertCompletion(cur, s, finished);
1055 }
1056
1057
1058 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1059         Dimension & dim) const
1060 {
1061         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1062         tm.completionPosAndDim(cur, x, y, dim);
1063 }
1064
1065
1066 string InsetText::contextMenu(BufferView const &, int, int) const
1067 {
1068         string context_menu = contextMenuName();
1069         if (context_menu != InsetText::contextMenuName())
1070                 context_menu += ";" + InsetText::contextMenuName();
1071         return context_menu;
1072 }
1073
1074
1075 string InsetText::contextMenuName() const
1076 {
1077         return "context-edit";
1078 }
1079
1080
1081 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1082 {
1083         OutputParams rp(&buffer().params().encoding());
1084         rp.for_tooltip = true;
1085         odocstringstream oss;
1086         oss << prefix;
1087
1088         ParagraphList::const_iterator beg = paragraphs().begin();
1089         ParagraphList::const_iterator end = paragraphs().end();
1090         ParagraphList::const_iterator it = beg;
1091         bool ref_printed = false;
1092
1093         for (; it != end; ++it) {
1094                 if (it != beg)
1095                         oss << '\n';
1096                 if ((*it).isRTL(buffer().params()))
1097                         oss << "<div dir=\"rtl\">";
1098                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1099                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1100                         break;
1101         }
1102         docstring str = oss.str();
1103         if (isChanged())
1104                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1105         support::truncateWithEllipsis(str, len);
1106         return str;
1107 }
1108
1109
1110 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1111 {
1112         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1113 }
1114
1115
1116 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1117 {
1118         // Nested cprotect content needs \cprotect
1119         // on each level
1120         if (producesOutput() && hasCProtectContent(fragile))
1121                 return true;
1122
1123         // Environments generally need cprotection in fragile context
1124         if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1125                 return true;
1126
1127         if (!getLayout().needsCProtect())
1128                 return false;
1129
1130         // Environments and "no latex" types (e.g., knitr chunks)
1131         // need cprotection regardless the content
1132         if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1133                 return true;
1134
1135         // If the inset does not produce output (e.g. Note or Branch),
1136         // we can ignore the contained paragraphs
1137         if (!producesOutput())
1138                 return false;
1139
1140         // Commands need cprotection if they contain specific chars
1141         int const nchars_escape = 9;
1142         static char_type const chars_escape[nchars_escape] = {
1143                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1144
1145         ParagraphList const & pars = paragraphs();
1146         pit_type pend = pit_type(paragraphs().size());
1147
1148         for (pit_type pit = 0; pit != pend; ++pit) {
1149                 Paragraph const & par = pars[size_type(pit)];
1150                 if (par.needsCProtection(fragile))
1151                         return true;
1152                 docstring const par_str = par.asString();
1153                 for (int k = 0; k < nchars_escape; k++) {
1154                         if (contains(par_str, chars_escape[k]))
1155                                 return true;
1156                 }
1157         }
1158         return false;
1159 }
1160
1161 } // namespace lyx