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