]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
DocBook: overall structure for rendered insets.
[features.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetLayout.h"
14 #include "InsetText.h"
15
16 #include "insets/InsetArgument.h"
17 #include "insets/InsetLayout.h"
18
19 #include "buffer_funcs.h"
20 #include "Buffer.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "CompletionList.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "InsetList.h"
32 #include "Intl.h"
33 #include "Language.h"
34 #include "Layout.h"
35 #include "LaTeXFeatures.h"
36 #include "Lexer.h"
37 #include "lyxfind.h"
38 #include "LyXRC.h"
39 #include "MetricsInfo.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_plaintext.h"
43 #include "output_xhtml.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TexRow.h"
48 #include "texstream.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53 #include "TocBuilder.h"
54
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
57
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/Changer.h"
64
65 #include <algorithm>
66 #include <stack>
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), intitle_context_(false),
82           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           intitle_context_(false), 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 += leftOffset(&bv) + rightOffset(&bv);
145         dim.des += bottomOffset(&bv);
146         dim.asc += topOffset(&bv);
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::setOuterFont(BufferView & bv, FontInfo const & outer) const
188 {
189         TextMetrics & tm = bv.textMetrics(&text_);
190         FontInfo tmpfont = getFont();
191         tmpfont.realize(outer);
192         tm.font_.fontInfo() = tmpfont;
193 }
194
195
196 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
197 {
198         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
199
200         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
201
202         int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
203         mi.base.textwidth -= horiz_offset;
204
205         // Remember the full outer font
206         setOuterFont(*mi.base.bv, mi.base.font);
207         // and use it in these metrics computation.
208         mi.base.font = tm.font_.fontInfo();
209
210         // This can happen when a layout has a left and right margin,
211         // and the view is made very narrow. We can't do better than
212         // to draw it partly out of view (bug 5890).
213         if (mi.base.textwidth < 1)
214                 mi.base.textwidth = 1;
215
216         if (hasFixedWidth())
217                 tm.metrics(mi, dim, mi.base.textwidth);
218         else
219                 tm.metrics(mi, dim);
220         mi.base.textwidth += horiz_offset;
221         dim.asc += topOffset(mi.base.bv);
222         dim.des += bottomOffset(mi.base.bv);
223         dim.wid += horiz_offset;
224 }
225
226
227 void InsetText::draw(PainterInfo & pi, int x, int y) const
228 {
229         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
230
231         int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
232         int const w = tm.width() + (horiz_offset - horiz_offset / 2);
233         int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
234         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
235         int const xframe = x + leftOffset(pi.base.bv) / 2;
236         bool change_drawn = false;
237         if (pi.full_repaint)
238                         pi.pain.fillRectangle(xframe, yframe, w, h,
239                                 pi.backgroundColor(this));
240
241         {
242                 Changer dummy = changeVar(pi.background_color,
243                                             pi.backgroundColor(this, false));
244                 // The change tracking cue must not be inherited
245                 Changer dummy2 = changeVar(pi.change, Change());
246                 tm.draw(pi, x + leftOffset(pi.base.bv), y);
247         }
248
249         if (drawFrame_) {
250                 // Change color of the frame in tracked changes, like for tabulars.
251                 // Only do so if the color is not custom. But do so even if RowPainter
252                 // handles the strike-through already.
253                 Color c;
254                 if (pi.change.changed()
255                     // Originally, these are the colors with role Text, from role() in
256                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
257                     // types, and also maybe it need not match in the future.
258                     && (frameColor() == Color_foreground
259                         || frameColor() == Color_cursor
260                         || frameColor() == Color_preview
261                         || frameColor() == Color_tabularline
262                         || frameColor() == Color_previewframe)) {
263                         c = pi.change.color();
264                         change_drawn = true;
265                 } else
266                         c = frameColor();
267                 pi.pain.rectangle(xframe, yframe, w, h, c);
268         }
269
270         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
271                 // Do not draw the change tracking cue if already done by RowPainter and
272                 // do not draw the cue for INSERTED if the information is already in the
273                 // color of the frame
274                 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
275 }
276
277
278 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
279 {
280         pit_type const pit = front ? 0 : paragraphs().size() - 1;
281         pos_type pos = front ? 0 : paragraphs().back().size();
282
283         // if visual information is not to be ignored, move to extreme right/left
284         if (entry_from != ENTRY_DIRECTION_IGNORE) {
285                 Cursor temp_cur = cur;
286                 temp_cur.pit() = pit;
287                 temp_cur.pos() = pos;
288                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
289                 pos = temp_cur.pos();
290         }
291
292         cur.top().setPitPos(pit, pos);
293         cur.setCurrentFont();
294         cur.finishUndo();
295 }
296
297
298 Inset * InsetText::editXY(Cursor & cur, int x, int y)
299 {
300         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
301 }
302
303
304 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
305 {
306         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
307
308 #if 0
309         // See bug #9042, for instance.
310         if (isPassThru()) {
311                 // Force any new text to latex_language FIXME: This
312                 // should only be necessary in constructor, but new
313                 // paragraphs that are created by pressing enter at
314                 // the start of an existing paragraph get the buffer
315                 // language and not latex_language, so we take this
316                 // brute force approach.
317                 cur.current_font.setLanguage(latex_language);
318                 cur.real_current_font.setLanguage(latex_language);
319         }
320 #endif
321
322         switch (cmd.action()) {
323         case LFUN_PASTE:
324         case LFUN_CLIPBOARD_PASTE:
325         case LFUN_SELECTION_PASTE:
326         case LFUN_PRIMARY_SELECTION_PASTE:
327                 text_.dispatch(cur, cmd);
328                 // If we we can only store plain text, we must reset all
329                 // attributes.
330                 // FIXME: Change only the pasted paragraphs
331                 fixParagraphsFont();
332                 break;
333
334         case LFUN_INSET_SPLIT:
335         case LFUN_INSET_DISSOLVE: {
336                 bool const main_inset = text_.isMainText();
337                 bool const target_inset = cmd.argument().empty()
338                         || cmd.getArg(0) == insetName(lyxCode());
339
340                 if (!main_inset && target_inset) {
341                         UndoGroupHelper ugh(&buffer());
342                         // Text::dissolveInset assumes that the cursor
343                         // is inside the Inset.
344                         if (&cur.inset() != this) {
345                                 cur.recordUndo();
346                                 cur.pushBackward(*this);
347                         }
348                         text_.dispatch(cur, cmd);
349                 } else
350                         cur.undispatched();
351                 break;
352         }
353
354         default:
355                 text_.dispatch(cur, cmd);
356         }
357
358         if (!cur.result().dispatched())
359                 Inset::doDispatch(cur, cmd);
360 }
361
362
363 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
364         FuncStatus & status) const
365 {
366         switch (cmd.action()) {
367         case LFUN_INSET_SPLIT:
368         case LFUN_INSET_DISSOLVE: {
369                 bool const main_inset = text_.isMainText();
370                 bool const target_inset = cmd.argument().empty()
371                         || cmd.getArg(0) == insetName(lyxCode());
372
373                 if (target_inset)
374                         status.setEnabled(!main_inset);
375                 return target_inset;
376         }
377
378         case LFUN_ARGUMENT_INSERT: {
379                 string const arg = cmd.getArg(0);
380                 if (arg.empty()) {
381                         status.setEnabled(false);
382                         return true;
383                 }
384                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
385                         return text_.getStatus(cur, cmd, status);
386
387                 Layout::LaTeXArgMap args = getLayout().args();
388                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
389                 if (lait != args.end()) {
390                         status.setEnabled(true);
391                         for (Paragraph const & par : paragraphs())
392                                 for (auto const & table : par.insetList())
393                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
394                                                 if (ins->name() == arg) {
395                                                         // we have this already
396                                                         status.setEnabled(false);
397                                                         return true;
398                                                 }
399                 } else
400                         status.setEnabled(false);
401                 return true;
402         }
403
404         default:
405                 // Dispatch only to text_ if the cursor is inside
406                 // the text_. It is not for context menus (bug 5797).
407                 bool ret = false;
408                 if (cur.text() == &text_)
409                         ret = text_.getStatus(cur, cmd, status);
410
411                 if (!ret)
412                         ret = Inset::getStatus(cur, cmd, status);
413                 return ret;
414         }
415 }
416
417
418 void InsetText::fixParagraphsFont()
419 {
420         Font font(inherit_font, buffer().params().language);
421         font.setLanguage(latex_language);
422         ParagraphList::iterator par = paragraphs().begin();
423         ParagraphList::iterator const end = paragraphs().end();
424         while (par != end) {
425                 if (par->isPassThru())
426                         par->resetFonts(font);
427                 if (!par->allowParagraphCustomization())
428                         par->params().clear();
429                 ++par;
430         }
431 }
432
433
434 // bool InsetText::isChanged() const
435 // {
436 //      ParagraphList::const_iterator pit = paragraphs().begin();
437 //      ParagraphList::const_iterator end = paragraphs().end();
438 //      for (; pit != end; ++pit) {
439 //              if (pit->isChanged())
440 //                      return true;
441 //      }
442 //      return false;
443 // }
444
445
446 void InsetText::setChange(Change const & change)
447 {
448         ParagraphList::iterator pit = paragraphs().begin();
449         ParagraphList::iterator end = paragraphs().end();
450         for (; pit != end; ++pit) {
451                 pit->setChange(change);
452         }
453 }
454
455
456 void InsetText::acceptChanges()
457 {
458         text_.acceptChanges();
459 }
460
461
462 void InsetText::rejectChanges()
463 {
464         text_.rejectChanges();
465 }
466
467
468 void InsetText::validate(LaTeXFeatures & features) const
469 {
470         features.useInsetLayout(getLayout());
471         for (Paragraph const & p : paragraphs())
472                 p.validate(features);
473 }
474
475
476 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
477 {
478         // This implements the standard way of handling the LaTeX
479         // output of a text inset, either a command or an
480         // environment. Standard collapsible insets should not
481         // redefine this, non-standard ones may call this.
482         InsetLayout const & il = getLayout();
483         if (il.forceOwnlines())
484                 os << breakln;
485         bool needendgroup = false;
486         if (!il.latexname().empty()) {
487                 if (il.latextype() == InsetLaTeXType::COMMAND) {
488                         // FIXME UNICODE
489                         // FIXME \protect should only be used for fragile
490                         //    commands, but we do not provide this information yet.
491                         if (hasCProtectContent(runparams.moving_arg)) {
492                                 if (contains(runparams.active_chars, '^')) {
493                                         // cprotect relies on ^ being on catcode 7
494                                         os << "\\begingroup\\catcode`\\^=7";
495                                         needendgroup = true;
496                                 }
497                                 os << "\\cprotect";
498                         } else if (runparams.moving_arg)
499                                 os << "\\protect";
500                         os << '\\' << from_utf8(il.latexname());
501                         if (!il.latexargs().empty())
502                                 getArgs(os, runparams);
503                         if (!il.latexparam().empty())
504                                 os << from_utf8(il.latexparam());
505                         os << '{';
506                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
507                         if (il.isDisplay())
508                                 os << breakln;
509                         else
510                                 os << safebreakln;
511                         if (runparams.lastid != -1)
512                                 os.texrow().start(runparams.lastid,
513                                                   runparams.lastpos);
514                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
515                         if (!il.latexargs().empty())
516                                 getArgs(os, runparams);
517                         if (!il.latexparam().empty())
518                                 os << from_utf8(il.latexparam());
519                         os << '\n';
520                 }
521         } else {
522                 if (!il.latexargs().empty())
523                         getArgs(os, runparams);
524                 if (!il.latexparam().empty())
525                         os << from_utf8(il.latexparam());
526         }
527
528         if (!il.leftdelim().empty())
529                 os << il.leftdelim();
530
531         OutputParams rp = runparams;
532         if (isPassThru())
533                 rp.pass_thru = true;
534         if (il.isNeedProtect())
535                 rp.moving_arg = true;
536         if (il.isNeedMBoxProtect())
537                 ++rp.inulemcmd;
538         if (!il.passThruChars().empty())
539                 rp.pass_thru_chars += il.passThruChars();
540         if (!il.newlineCmd().empty())
541                 rp.newlinecmd = il.newlineCmd();
542         rp.par_begin = 0;
543         rp.par_end = paragraphs().size();
544
545         // Output the contents of the inset
546         latexParagraphs(buffer(), text_, os, rp);
547         runparams.encoding = rp.encoding;
548         // Pass the post_macros upstream
549         runparams.post_macro = rp.post_macro;
550         // These need to be passed upstream as well
551         runparams.need_maketitle = rp.need_maketitle;
552         runparams.have_maketitle = rp.have_maketitle;
553
554         if (!il.rightdelim().empty())
555                 os << il.rightdelim();
556
557         if (!il.latexname().empty()) {
558                 if (il.latextype() == InsetLaTeXType::COMMAND) {
559                         os << "}";
560                         if (!il.postcommandargs().empty())
561                                 getArgs(os, runparams, true);
562                         if (needendgroup)
563                                 os << "\\endgroup";
564                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
565                         // A comment environment doesn't need a % before \n\end
566                         if (il.isDisplay() || runparams.inComment)
567                                 os << breakln;
568                         else
569                                 os << safebreakln;
570                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
571                         if (!il.isDisplay())
572                                 os.protectSpace(true);
573                 }
574         }
575         if (il.forceOwnlines())
576                 os << breakln;
577 }
578
579
580 int InsetText::plaintext(odocstringstream & os,
581         OutputParams const & runparams, size_t max_length) const
582 {
583         ParagraphList::const_iterator beg = paragraphs().begin();
584         ParagraphList::const_iterator end = paragraphs().end();
585         ParagraphList::const_iterator it = beg;
586         bool ref_printed = false;
587         int len = 0;
588         for (; it != end; ++it) {
589                 if (it != beg) {
590                         os << '\n';
591                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
592                                 os << '\n';
593                 }
594                 odocstringstream oss;
595                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
596                 docstring const str = oss.str();
597                 os << str;
598                 // FIXME: len is not computed fully correctly; in principle,
599                 // we have to count the characters after the last '\n'
600                 len = str.size();
601                 if (os.str().size() >= max_length)
602                         break;
603         }
604
605         return len;
606 }
607
608
609 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
610 {
611         docbook(xs, rp, WriteEverything);
612 }
613
614
615 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
616 {
617         // Always output all the paragraphs.
618         OutputParams runparams = rp;
619         runparams.par_begin = 0;
620         runparams.par_end = text().paragraphs().size();
621
622         if (undefined()) {
623                 xs.startDivision(false);
624                 docbookParagraphs(text_, buffer(), xs, runparams);
625                 xs.endDivision();
626                 return;
627         }
628
629         InsetLayout const &il = getLayout();
630
631         // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
632         // else, typically outside the current paragraph).
633         if (!rp.docbook_generate_info && il.docbookininfo() != "never")
634                 return;
635
636         // Maybe this inset must be rendered before being output.
637         if (il.docbookrenderasimage()) {
638                 docbookRenderAsImage(xs, runparams, opts);
639                 return;
640         }
641
642         // If none of the special cases before apply, output the inset.
643         docbookText(xs, runparams, opts);
644 }
645
646
647 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
648 {
649         LASSERT(getLayout().docbookrenderasimage(), return);
650
651         // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
652         xs << xml::StartTag("mediaobject")
653            << xml::CR();
654
655         // Output the rendered inset.
656         xs << xml::StartTag("imageobject")
657            << xml::CR();
658         xs << xml::EndTag("imageobject")
659            << xml::CR();
660
661         // Output the raw content.
662         xs << xml::StartTag("textobject")
663            << xml::CR()
664            << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
665         docbookText(xs, rp, opts);
666         xs << xml::EndTag("programlisting")
667            << xml::CR()
668            << xml::EndTag("textobject")
669            << xml::CR();
670
671         xs << xml::EndTag("mediaobject")
672            << xml::CR();
673 }
674
675
676 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
677 {
678         InsetLayout const &il = getLayout();
679         OutputParams runparams = rp;
680
681         // In some cases, the input parameters must be overridden for outer tags.
682         bool writeOuterTag = opts & WriteOuterTag;
683         if (writeOuterTag) {
684                 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
685                 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
686                         auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
687                         auto parSize = (size_t) par.size();
688                         return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
689                 });
690                 writeOuterTag = !allBibitems;
691         }
692
693         // Detect arguments that should be output before/after the paragraph.
694         // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
695         // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
696         std::set<InsetArgument const *> prependedArguments;
697         for (auto const & par : paragraphs()) {
698                 for (pos_type i = 0; i < par.size(); ++i) {
699                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
700                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
701                                 if (arg->docbookargumentbeforemaintag())
702                                         prependedArguments.insert(par.getInset(i)->asInsetArgument());
703                         }
704                 }
705         }
706
707         std::set<InsetArgument const *> appendedArguments;
708         for (auto const & par : paragraphs()) {
709                 for (pos_type i = 0; i < par.size(); ++i) {
710                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
711                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
712                                 if (arg->docbookargumentaftermaintag())
713                                         appendedArguments.insert(par.getInset(i)->asInsetArgument());
714                         }
715                 }
716         }
717
718         // Start outputting this inset.
719         // - First, wrapper around the inset and its main tag.
720         if (writeOuterTag) {
721                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
722                         xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
723
724                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
725                         docstring attrs = docstring();
726                         if (!il.docbookattr().empty())
727                                 attrs += from_ascii(il.docbookattr());
728                         if (il.docbooktag() == "link")
729                                 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
730                         xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
731                 }
732
733                 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
734                         xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
735         }
736
737         // - Think about the arguments before the paragraph.
738         OutputParams np = runparams;
739         np.docbook_in_par = true;
740         for (auto const & arg : prependedArguments)
741                 arg->docbook(xs, np);
742
743         // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
744         runparams.docbook_prepended_arguments = std::move(prependedArguments);
745         runparams.docbook_appended_arguments = appendedArguments;
746
747         // - Deal with the first item.
748         // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
749         if (writeOuterTag) {
750                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
751                         xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
752
753                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
754                         xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
755         }
756
757         // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
758
759         // With respect to XHTML, paragraphs are still allowed here.
760         if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
761                 runparams.docbook_make_pars = false;
762         if (il.isPassThru())
763                 runparams.pass_thru = true;
764
765         // - Write the main content of the inset.
766         xs.startDivision(false);
767         docbookParagraphs(text_, buffer(), xs, runparams);
768         xs.endDivision();
769
770         // - Think about the arguments after the paragraph.
771         for (auto const & arg : appendedArguments)
772                 arg->docbook(xs, np);
773
774         // - Close the required tags.
775         if (writeOuterTag) {
776                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
777                         xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
778
779                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
780                         xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
781
782                 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
783                         xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
784
785                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
786                         xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
787
788                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
789                         xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
790         }
791 }
792
793
794 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
795 {
796         return insetAsXHTML(xs, runparams, WriteEverything);
797 }
798
799
800 // FIXME XHTML
801 // There are cases where we may need to close open fonts and such
802 // and then re-open them when we are done. This would be the case, e.g.,
803 // if we were otherwise about to write:
804 //              <em>word <div class='foot'>footnote text.</div> emph</em>
805 // The problem isn't so much that the footnote text will get emphasized:
806 // we can handle that with CSS. The problem is that this is invalid XHTML.
807 // One solution would be to make the footnote <span>, but the problem is
808 // completely general, and so we'd have to make absolutely everything into
809 // span. What I think will work is to check if we're about to write "div" and,
810 // if so, try to close fonts, etc.
811 // There are probably limits to how well we can do here, though, and we will
812 // have to rely upon users not putting footnotes inside noun-type insets.
813 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
814                                   XHTMLOptions opts) const
815 {
816         // we will always want to output all our paragraphs when we are
817         // called this way.
818         OutputParams runparams = rp;
819         runparams.par_begin = 0;
820         runparams.par_end = text().paragraphs().size();
821
822         if (undefined()) {
823                 xs.startDivision(false);
824                 xhtmlParagraphs(text_, buffer(), xs, runparams);
825                 xs.endDivision();
826                 return docstring();
827         }
828
829         InsetLayout const & il = getLayout();
830         if (opts & WriteOuterTag)
831                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
832
833         if ((opts & WriteLabel) && !il.counter().empty()) {
834                 BufferParams const & bp = buffer().masterBuffer()->params();
835                 Counters & cntrs = bp.documentClass().counters();
836                 cntrs.step(il.counter(), OutputUpdate);
837                 // FIXME: translate to paragraph language
838                 if (!il.htmllabel().empty()) {
839                         docstring const lbl =
840                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
841                         // FIXME is this check necessary?
842                         if (!lbl.empty()) {
843                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
844                                 xs << lbl;
845                                 xs << xml::EndTag(il.htmllabeltag());
846                         }
847                 }
848         }
849
850         if (opts & WriteInnerTag)
851                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
852
853         // we will eventually lose information about the containing inset
854         if (!allowMultiPar() || opts == JustText)
855                 runparams.html_make_pars = false;
856         if (il.isPassThru())
857                 runparams.pass_thru = true;
858
859         xs.startDivision(false);
860         xhtmlParagraphs(text_, buffer(), xs, runparams);
861         xs.endDivision();
862
863         if (opts & WriteInnerTag)
864                 xs << xml::EndTag(il.htmlinnertag());
865
866         if (opts & WriteOuterTag)
867                 xs << xml::EndTag(il.htmltag());
868
869         return docstring();
870 }
871
872
873 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
874                         bool const post) const
875 {
876         OutputParams runparams = runparams_in;
877         runparams.local_font =
878                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
879         if (isPassThru())
880                 runparams.pass_thru = true;
881         if (post)
882                 latexArgInsetsForParent(paragraphs(), os, runparams,
883                                         getLayout().postcommandargs(), "post:");
884         else
885                 latexArgInsetsForParent(paragraphs(), os, runparams,
886                                         getLayout().latexargs());
887 }
888
889
890 void InsetText::cursorPos(BufferView const & bv,
891                 CursorSlice const & sl, bool boundary, int & x, int & y) const
892 {
893         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
894         y = bv.textMetrics(&text_).cursorY(sl, boundary);
895 }
896
897
898 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
899 {
900         clear();
901         Paragraph & first = paragraphs().front();
902         for (unsigned int i = 0; i < data.length(); ++i)
903                 first.insertChar(i, data[i], font, trackChanges);
904 }
905
906
907 void InsetText::setDrawFrame(bool flag)
908 {
909         drawFrame_ = flag;
910 }
911
912
913 ColorCode InsetText::frameColor() const
914 {
915         return frame_color_;
916 }
917
918
919 void InsetText::setFrameColor(ColorCode col)
920 {
921         frame_color_ = col;
922 }
923
924
925 void InsetText::appendParagraphs(ParagraphList & plist)
926 {
927         // There is little we can do here to keep track of changes.
928         // As of 2006/10/20, appendParagraphs is used exclusively by
929         // LyXTabular::setMultiColumn. In this context, the paragraph break
930         // is lost irreversibly and the appended text doesn't really change
931
932         ParagraphList & pl = paragraphs();
933
934         ParagraphList::iterator pit = plist.begin();
935         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
936         ++pit;
937         mergeParagraph(buffer().params(), pl,
938                        distance(pl.begin(), ins) - 1);
939
940         ParagraphList::iterator const pend = plist.end();
941         for (; pit != pend; ++pit)
942                 pl.push_back(*pit);
943 }
944
945
946 void InsetText::addPreview(DocIterator const & text_inset_pos,
947         PreviewLoader & loader) const
948 {
949         ParagraphList::const_iterator pit = paragraphs().begin();
950         ParagraphList::const_iterator pend = paragraphs().end();
951         int pidx = 0;
952
953         DocIterator inset_pos = text_inset_pos;
954         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
955
956         for (; pit != pend; ++pit, ++pidx) {
957                 InsetList::const_iterator it  = pit->insetList().begin();
958                 InsetList::const_iterator end = pit->insetList().end();
959                 inset_pos.pit() = pidx;
960                 for (; it != end; ++it) {
961                         inset_pos.pos() = it->pos;
962                         it->inset->addPreview(inset_pos, loader);
963                 }
964         }
965 }
966
967
968 ParagraphList const & InsetText::paragraphs() const
969 {
970         return text_.paragraphs();
971 }
972
973
974 ParagraphList & InsetText::paragraphs()
975 {
976         return text_.paragraphs();
977 }
978
979
980 bool InsetText::hasCProtectContent(bool fragile) const
981 {
982         fragile |= getLayout().isNeedProtect();
983         ParagraphList const & pars = paragraphs();
984         pit_type pend = pit_type(paragraphs().size());
985         for (pit_type pit = 0; pit != pend; ++pit) {
986                 Paragraph const & par = pars[size_type(pit)];
987                 if (par.needsCProtection(fragile))
988                         return true;
989         }
990         return false;
991 }
992
993
994 bool InsetText::insetAllowed(InsetCode code) const
995 {
996         switch (code) {
997         // Arguments, (plain) quotes and counter insets 
998         // are also allowed in PassThru insets
999         case ARG_CODE:
1000         case QUOTE_CODE:
1001         case COUNTER_CODE:
1002                 return true;
1003         default:
1004                 return !isPassThru();
1005         }
1006 }
1007
1008
1009 bool InsetText::allowSpellCheck() const
1010 {
1011         return getLayout().spellcheck() && !getLayout().isPassThru();
1012 }
1013
1014
1015 bool InsetText::allowMultiPar() const
1016 {
1017         return getLayout().isMultiPar();
1018 }
1019
1020
1021 bool InsetText::forcePlainLayout(idx_type) const
1022 {
1023         return getLayout().forcePlainLayout();
1024 }
1025
1026
1027 bool InsetText::allowParagraphCustomization(idx_type) const
1028 {
1029         return getLayout().allowParagraphCustomization();
1030 }
1031
1032
1033 bool InsetText::forceLocalFontSwitch() const
1034 {
1035         return getLayout().forceLocalFontSwitch();
1036 }
1037
1038
1039 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1040 {
1041         ParIterator it2 = it;
1042         it2.forwardPos();
1043         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1044         if (producesOutput()) {
1045                 InsetLayout const & il = getLayout();
1046                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1047                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1048                 if (save_layouts) {
1049                         // LYXERR0("Entering " << name());
1050                         cnt.clearLastLayout();
1051                         // FIXME cnt.saveLastCounter()?
1052                 }
1053                 buffer().updateBuffer(it2, utype, deleted);
1054                 if (save_layouts) {
1055                         // LYXERR0("Exiting " << name());
1056                         cnt.restoreLastLayout();
1057                         // FIXME cnt.restoreLastCounter()?
1058                 }
1059                 // Record if this inset is embedded in a title layout
1060                 // This is needed to decide when \maketitle is output.
1061                 intitle_context_ = it.paragraph().layout().intitle;
1062                 // Also check embedding layouts
1063                 size_t const n = it.depth();
1064                 for (size_t i = 0; i < n; ++i) {
1065                         if (it[i].paragraph().layout().intitle) {
1066                                 intitle_context_ = true;
1067                                 break;
1068                         }
1069                 }
1070         } else {
1071                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1072                 // Note that we do not need to call:
1073                 //      tclass.counters().clearLastLayout()
1074                 // since we are saving and restoring the existing counters, etc.
1075                 Counters savecnt = tclass.counters();
1076                 tclass.counters().reset();
1077                 // we need float information even in note insets (#9760)
1078                 tclass.counters().current_float(savecnt.current_float());
1079                 tclass.counters().isSubfloat(savecnt.isSubfloat());
1080                 buffer().updateBuffer(it2, utype, deleted);
1081                 tclass.counters() = move(savecnt);
1082         }
1083 }
1084
1085
1086 void InsetText::toString(odocstream & os) const
1087 {
1088         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1089 }
1090
1091
1092 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1093                                                         bool const shorten) const
1094 {
1095         if (!getLayout().isInToc())
1096                 return;
1097         text().forOutliner(os, maxlen, shorten);
1098 }
1099
1100
1101 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1102                                                  UpdateType utype, TocBackend & backend) const
1103 {
1104         DocIterator dit = cdit;
1105         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1106         iterateForToc(dit, output_active, utype, backend);
1107 }
1108
1109
1110 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1111                                                           UpdateType utype, TocBackend & backend) const
1112 {
1113         DocIterator dit = cdit;
1114         // This also ensures that any document has a table of contents
1115         shared_ptr<Toc> toc = backend.toc("tableofcontents");
1116
1117         BufferParams const & bufparams = buffer_->params();
1118         int const min_toclevel = bufparams.documentClass().min_toclevel();
1119         // we really should have done this before we got here, but it
1120         // can't hurt too much to do it again
1121         bool const doing_output = output_active && producesOutput();
1122
1123         // For each paragraph,
1124         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1125         //   paragraphs as needed.
1126         // * Traverse its insets and let them add their toc items
1127         // * Compute the main table of contents (this is hardcoded)
1128         // * Add the list of changes
1129         ParagraphList const & pars = paragraphs();
1130         pit_type pend = paragraphs().size();
1131         // Record pairs {start,end} of where a toc item was opened for a paragraph
1132         // and where it must be closed
1133         stack<pair<pit_type, pit_type>> addtotoc_stack;
1134
1135         for (pit_type pit = 0; pit != pend; ++pit) {
1136                 Paragraph const & par = pars[pit];
1137                 dit.pit() = pit;
1138                 dit.pos() = 0;
1139
1140                 // Custom AddToToc in paragraph layouts (i.e. theorems)
1141                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1142                         pit_type end =
1143                                 openAddToTocForParagraph(pit, dit, output_active, backend);
1144                         addtotoc_stack.push({pit, end});
1145                 }
1146
1147                 // If we find an InsetArgument that is supposed to provide the TOC caption,
1148                 // we'll save it for use later.
1149                 InsetArgument const * arginset = nullptr;
1150                 for (auto const & table : par.insetList()) {
1151                         dit.pos() = table.pos;
1152                         table.inset->addToToc(dit, doing_output, utype, backend);
1153                         if (InsetArgument const * x = table.inset->asInsetArgument())
1154                                 if (x->isTocCaption())
1155                                         arginset = x;
1156                 }
1157
1158                 // End custom AddToToc in paragraph layouts
1159                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1160                         // execute the closing function
1161                         closeAddToTocForParagraph(addtotoc_stack.top().first,
1162                                                   addtotoc_stack.top().second, backend);
1163                         addtotoc_stack.pop();
1164                 }
1165
1166                 // now the toc entry for the paragraph in the main table of contents
1167                 int const toclevel = text().getTocLevel(pit);
1168                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1169                         // insert this into the table of contents
1170                         docstring tocstring;
1171                         int const length = (doing_output && utype == OutputUpdate) ?
1172                                 INT_MAX : TOC_ENTRY_LENGTH;
1173                         if (arginset) {
1174                                 tocstring = par.labelString();
1175                                 if (!tocstring.empty())
1176                                         tocstring += ' ';
1177                                 arginset->text().forOutliner(tocstring, length);
1178                         } else
1179                                 par.forOutliner(tocstring, length);
1180                         dit.pos() = 0;
1181                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1182                                                tocstring, doing_output));
1183                 }
1184
1185                 // And now the list of changes.
1186                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1187         }
1188 }
1189
1190
1191 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1192                                              DocIterator const & dit,
1193                                              bool output_active,
1194                                              TocBackend & backend) const
1195 {
1196         Paragraph const & par = paragraphs()[pit];
1197         TocBuilder & b = backend.builder(par.layout().tocType());
1198         docstring const & label = par.labelString();
1199         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1200         return text().lastInSequence(pit);
1201 }
1202
1203
1204 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1205                                           TocBackend & backend) const
1206 {
1207         Paragraph const & par = paragraphs()[start];
1208         TocBuilder & b = backend.builder(par.layout().tocType());
1209         if (par.layout().isTocCaption()) {
1210                 docstring str;
1211                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1212                 b.argumentItem(str);
1213         }
1214         b.pop();
1215 }
1216
1217
1218 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1219 {
1220         if (buffer().isClean())
1221                 return Inset::notifyCursorLeaves(old, cur);
1222
1223         // find text inset in old cursor
1224         Cursor insetCur = old;
1225         int scriptSlice = insetCur.find(this);
1226         // we can try to continue here. returning true means
1227         // the cursor is "now" invalid. which it was.
1228         LASSERT(scriptSlice != -1, return true);
1229         insetCur.cutOff(scriptSlice);
1230         LASSERT(&insetCur.inset() == this, return true);
1231
1232         // update the old paragraph's words
1233         insetCur.paragraph().updateWords();
1234
1235         return Inset::notifyCursorLeaves(old, cur);
1236 }
1237
1238
1239 bool InsetText::completionSupported(Cursor const & cur) const
1240 {
1241         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1242         return text_.completionSupported(cur);
1243 }
1244
1245
1246 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1247 {
1248         return completionSupported(cur);
1249 }
1250
1251
1252 bool InsetText::automaticInlineCompletion() const
1253 {
1254         return lyxrc.completion_inline_text;
1255 }
1256
1257
1258 bool InsetText::automaticPopupCompletion() const
1259 {
1260         return lyxrc.completion_popup_text;
1261 }
1262
1263
1264 bool InsetText::showCompletionCursor() const
1265 {
1266         return lyxrc.completion_cursor_text &&
1267                 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1268 }
1269
1270
1271 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1272 {
1273         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1274 }
1275
1276
1277 docstring InsetText::completionPrefix(Cursor const & cur) const
1278 {
1279         if (!completionSupported(cur))
1280                 return docstring();
1281         return text_.completionPrefix(cur);
1282 }
1283
1284
1285 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1286         bool finished)
1287 {
1288         if (!completionSupported(cur))
1289                 return false;
1290
1291         return text_.insertCompletion(cur, s, finished);
1292 }
1293
1294
1295 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1296         Dimension & dim) const
1297 {
1298         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1299         tm.completionPosAndDim(cur, x, y, dim);
1300 }
1301
1302
1303 string InsetText::contextMenu(BufferView const &, int, int) const
1304 {
1305         string context_menu = contextMenuName();
1306         if (context_menu != InsetText::contextMenuName())
1307                 context_menu += ";" + InsetText::contextMenuName();
1308         return context_menu;
1309 }
1310
1311
1312 string InsetText::contextMenuName() const
1313 {
1314         return "context-edit";
1315 }
1316
1317
1318 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1319 {
1320         OutputParams rp(&buffer().params().encoding());
1321         rp.for_tooltip = true;
1322         odocstringstream oss;
1323         oss << prefix;
1324
1325         ParagraphList::const_iterator beg = paragraphs().begin();
1326         ParagraphList::const_iterator end = paragraphs().end();
1327         ParagraphList::const_iterator it = beg;
1328         bool ref_printed = false;
1329
1330         for (; it != end; ++it) {
1331                 if (it != beg)
1332                         oss << '\n';
1333                 if ((*it).isRTL(buffer().params()))
1334                         oss << "<div dir=\"rtl\">";
1335                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1336                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1337                         break;
1338         }
1339         docstring str = oss.str();
1340         if (isChanged())
1341                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1342         support::truncateWithEllipsis(str, len);
1343         return str;
1344 }
1345
1346
1347 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1348 {
1349         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1350 }
1351
1352
1353 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1354 {
1355         // Nested cprotect content needs \cprotect
1356         // on each level
1357         if (producesOutput() && hasCProtectContent(fragile))
1358                 return true;
1359
1360         // Environments generally need cprotection in fragile context
1361         if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1362                 return true;
1363
1364         if (!getLayout().needsCProtect())
1365                 return false;
1366
1367         // Environments and "no latex" types (e.g., knitr chunks)
1368         // need cprotection regardless the content
1369         if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1370                 return true;
1371
1372         // If the inset does not produce output (e.g. Note or Branch),
1373         // we can ignore the contained paragraphs
1374         if (!producesOutput())
1375                 return false;
1376
1377         // Commands need cprotection if they contain specific chars
1378         int const nchars_escape = 9;
1379         static char_type const chars_escape[nchars_escape] = {
1380                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1381
1382         ParagraphList const & pars = paragraphs();
1383         pit_type pend = pit_type(paragraphs().size());
1384
1385         for (pit_type pit = 0; pit != pend; ++pit) {
1386                 Paragraph const & par = pars[size_type(pit)];
1387                 if (par.needsCProtection(fragile))
1388                         return true;
1389                 docstring const par_str = par.asString();
1390                 for (int k = 0; k < nchars_escape; k++) {
1391                         if (contains(par_str, chars_escape[k]))
1392                                 return true;
1393                 }
1394         }
1395         return false;
1396 }
1397
1398 } // namespace lyx