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