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