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