]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Always qualify calls to std::move()
[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/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                 break;
338
339         case LFUN_INSET_SPLIT:
340         case LFUN_INSET_DISSOLVE: {
341                 bool const main_inset = text_.isMainText();
342                 bool const target_inset = cmd.argument().empty()
343                         || cmd.getArg(0) == insetName(lyxCode());
344
345                 if (!main_inset && target_inset) {
346                         UndoGroupHelper ugh(&buffer());
347                         // Text::dissolveInset assumes that the cursor
348                         // is inside the Inset.
349                         if (&cur.inset() != this) {
350                                 cur.recordUndo();
351                                 cur.pushBackward(*this);
352                         }
353                         text_.dispatch(cur, cmd);
354                 } else
355                         cur.undispatched();
356                 break;
357         }
358
359         default:
360                 text_.dispatch(cur, cmd);
361         }
362
363         if (!cur.result().dispatched())
364                 Inset::doDispatch(cur, cmd);
365 }
366
367
368 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
369         FuncStatus & status) const
370 {
371         switch (cmd.action()) {
372         case LFUN_INSET_SPLIT:
373         case LFUN_INSET_DISSOLVE: {
374                 bool const main_inset = text_.isMainText();
375                 bool const target_inset = cmd.argument().empty()
376                         || cmd.getArg(0) == insetName(lyxCode());
377
378                 if (target_inset)
379                         status.setEnabled(!main_inset);
380                 return target_inset;
381         }
382
383         case LFUN_ARGUMENT_INSERT: {
384                 string const arg = cmd.getArg(0);
385                 if (arg.empty()) {
386                         status.setEnabled(false);
387                         return true;
388                 }
389                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
390                         return text_.getStatus(cur, cmd, status);
391
392                 Layout::LaTeXArgMap args = getLayout().args();
393                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
394                 if (lait != args.end()) {
395                         status.setEnabled(true);
396                         for (Paragraph const & par : paragraphs())
397                                 for (auto const & table : par.insetList())
398                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
399                                                 if (ins->name() == arg) {
400                                                         // we have this already
401                                                         status.setEnabled(false);
402                                                         return true;
403                                                 }
404                 } else
405                         status.setEnabled(false);
406                 return true;
407         }
408
409         default:
410                 // Dispatch only to text_ if the cursor is inside
411                 // the text_. It is not for context menus (bug 5797).
412                 bool ret = false;
413                 if (cur.text() == &text_)
414                         ret = text_.getStatus(cur, cmd, status);
415
416                 if (!ret)
417                         ret = Inset::getStatus(cur, cmd, status);
418                 return ret;
419         }
420 }
421
422
423 void InsetText::fixParagraphsFont()
424 {
425         Font font(inherit_font, buffer().params().language);
426         font.setLanguage(latex_language);
427         ParagraphList::iterator par = paragraphs().begin();
428         ParagraphList::iterator const end = paragraphs().end();
429         while (par != end) {
430                 if (par->isPassThru())
431                         par->resetFonts(font);
432                 if (!par->allowParagraphCustomization())
433                         par->params().clear();
434                 ++par;
435         }
436 }
437
438
439 // bool InsetText::isChanged() const
440 // {
441 //      ParagraphList::const_iterator pit = paragraphs().begin();
442 //      ParagraphList::const_iterator end = paragraphs().end();
443 //      for (; pit != end; ++pit) {
444 //              if (pit->isChanged())
445 //                      return true;
446 //      }
447 //      return false;
448 // }
449
450
451 void InsetText::setChange(Change const & change)
452 {
453         ParagraphList::iterator pit = paragraphs().begin();
454         ParagraphList::iterator end = paragraphs().end();
455         for (; pit != end; ++pit) {
456                 pit->setChange(change);
457         }
458 }
459
460
461 void InsetText::acceptChanges()
462 {
463         text_.acceptChanges();
464 }
465
466
467 void InsetText::rejectChanges()
468 {
469         text_.rejectChanges();
470 }
471
472
473 void InsetText::validate(LaTeXFeatures & features) const
474 {
475         features.useInsetLayout(getLayout());
476         for (Paragraph const & p : paragraphs())
477                 p.validate(features);
478 }
479
480
481 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
482 {
483         // This implements the standard way of handling the LaTeX
484         // output of a text inset, either a command or an
485         // environment. Standard collapsible insets should not
486         // redefine this, non-standard ones may call this.
487         InsetLayout const & il = getLayout();
488
489         if (il.forceOwnlines())
490                 os << breakln;
491         bool needendgroup = false;
492         if (!il.latexname().empty()) {
493                 if (il.latextype() == InsetLaTeXType::COMMAND) {
494                         // FIXME UNICODE
495                         // FIXME \protect should only be used for fragile
496                         //    commands, but we do not provide this information yet.
497                         if (hasCProtectContent(runparams.moving_arg)) {
498                                 if (contains(runparams.active_chars, '^')) {
499                                         // cprotect relies on ^ being on catcode 7
500                                         os << "\\begingroup\\catcode`\\^=7";
501                                         needendgroup = true;
502                                 }
503                                 os << "\\cprotect";
504                         } else if (runparams.moving_arg)
505                                 os << "\\protect";
506                         os << '\\' << from_utf8(il.latexname());
507                         if (!il.latexargs().empty())
508                                 getArgs(os, runparams);
509                         if (!il.latexparam().empty())
510                                 os << from_utf8(il.latexparam());
511                         os << '{';
512                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
513                         if (il.isDisplay())
514                                 os << breakln;
515                         else
516                                 os << safebreakln;
517                         if (runparams.lastid != -1)
518                                 os.texrow().start(runparams.lastid,
519                                                   runparams.lastpos);
520                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
521                         if (!il.latexargs().empty())
522                                 getArgs(os, runparams);
523                         if (!il.latexparam().empty())
524                                 os << from_utf8(il.latexparam());
525                         os << '\n';
526                 }
527         } else {
528                 if (!il.latexargs().empty())
529                         getArgs(os, runparams);
530                 if (!il.latexparam().empty())
531                         os << from_utf8(il.latexparam());
532         }
533
534         if (!il.leftdelim().empty())
535                 os << il.leftdelim();
536
537         OutputParams rp = runparams;
538         if (isPassThru())
539                 rp.pass_thru = true;
540         if (il.isNeedProtect())
541                 rp.moving_arg = true;
542         if (il.isNeedMBoxProtect())
543                 ++rp.inulemcmd;
544         if (!il.passThruChars().empty())
545                 rp.pass_thru_chars += il.passThruChars();
546         if (!il.newlineCmd().empty())
547                 rp.newlinecmd = il.newlineCmd();
548         rp.par_begin = 0;
549         rp.par_end = paragraphs().size();
550
551         // Output the contents of the inset
552         latexParagraphs(buffer(), text_, os, rp);
553         runparams.encoding = rp.encoding;
554         // Pass the post_macros upstream
555         runparams.post_macro = rp.post_macro;
556         // These need to be passed upstream as well
557         runparams.need_maketitle = rp.need_maketitle;
558         runparams.have_maketitle = rp.have_maketitle;
559
560         if (!il.rightdelim().empty())
561                 os << il.rightdelim();
562
563         if (!il.latexname().empty()) {
564                 if (il.latextype() == InsetLaTeXType::COMMAND) {
565                         os << "}";
566                         if (!il.postcommandargs().empty())
567                                 getArgs(os, runparams, true);
568                         if (needendgroup)
569                                 os << "\\endgroup";
570                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
571                         // A comment environment doesn't need a % before \n\end
572                         if (il.isDisplay() || runparams.inComment)
573                                 os << breakln;
574                         else
575                                 os << safebreakln;
576                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
577                         if (!il.isDisplay())
578                                 os.protectSpace(true);
579                 }
580         }
581         if (il.forceOwnlines())
582                 os << breakln;
583 }
584
585
586 int InsetText::plaintext(odocstringstream & os,
587         OutputParams const & runparams, size_t max_length) const
588 {
589         ParagraphList::const_iterator beg = paragraphs().begin();
590         ParagraphList::const_iterator end = paragraphs().end();
591         ParagraphList::const_iterator it = beg;
592         bool ref_printed = false;
593         int len = 0;
594         for (; it != end; ++it) {
595                 if (it != beg) {
596                         os << '\n';
597                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
598                                 os << '\n';
599                 }
600                 odocstringstream oss;
601                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
602                 docstring const str = oss.str();
603                 os << str;
604                 // FIXME: len is not computed fully correctly; in principle,
605                 // we have to count the characters after the last '\n'
606                 len = str.size();
607                 if (os.str().size() >= max_length)
608                         break;
609         }
610
611         return len;
612 }
613
614
615 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
616 {
617         docbook(xs, rp, WriteEverything);
618 }
619
620
621 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
622 {
623         // Always output all the paragraphs.
624         OutputParams runparams = rp;
625         runparams.par_begin = 0;
626         runparams.par_end = text().paragraphs().size();
627
628         if (undefined()) {
629                 xs.startDivision(false);
630                 docbookParagraphs(text_, buffer(), xs, runparams);
631                 xs.endDivision();
632                 return;
633         }
634
635         InsetLayout const &il = getLayout();
636
637         // Maybe this is an <info> paragraph that should not be generated
638         // at all (i.e. right now, its place is somewhere else, typically outside
639         // the current paragraph).
640         if (!rp.docbook_generate_info && il.docbookininfo() != "never")
641                 return;
642
643         // Maybe this inset must be rendered before being output.
644         if (il.docbookrenderasimage()) {
645                 docbookRenderAsImage(xs, runparams, opts);
646                 return;
647         }
648
649         // If none of the special cases before apply, output the inset.
650         docbookText(xs, runparams, opts);
651 }
652
653
654 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
655 {
656         LASSERT(getLayout().docbookrenderasimage(), return);
657
658         // Generate the LaTeX code to compile in order to get the image.
659         // This code actually does the same as an InsetPreview, but without
660         // an InsetPreview.
661         // Also, the image must be generated before the DocBook output is finished,
662         // unlike a preview that is not immediately required for display.
663         docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
664         std::string const snippet = support::trim(to_utf8(latex_snippet));
665         // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
666
667         graphics::PreviewLoader* loader = buffer().loader();
668         // This should be OK because we are exporting
669         LASSERT(loader != nullptr, return);
670         loader->add(snippet);
671         loader->startLoading(true); // Generate the image and wait until done.
672         graphics::PreviewImage const * img = loader->preview(snippet);
673         LASSERT(img != nullptr, return);
674         support::FileName const & filename = img->filename();
675
676         // Use a file name that is only determined by the LaTeX code: the name of
677         // the snippet is more or less random (i.e., if the user generates the file
678         // several times, they will have a clutter of preview files).
679         // Hence: use a cryptographic hash of the snippet. If the snippet changes,
680         // the file name will change a lot; two snippets are unlikely to have the
681         // same hash (by design of cryptographic hash functions). Computing a hash
682         // is typically slow, but extremely fast compared to compilation of the
683         // preview and image rendering.
684         std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(snippet)) + "." + filename.extension();
685
686         // Copy the image into the right folder.
687         rp.exportdata->addExternalFile("docbook5", filename, newFileName);
688
689         // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
690         // Start writing the DocBook code for the image.
691         xs << xml::StartTag("mediaobject")
692            << xml::CR();
693
694         // Output the rendered inset.
695         xs << xml::StartTag("imageobject")
696            << xml::CR()
697            << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
698            << xml::CR()
699            << xml::EndTag("imageobject")
700            << xml::CR();
701
702         // Output the raw content.
703         xs << xml::StartTag("textobject")
704            << xml::CR()
705            << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
706         docbookText(xs, rp, opts);
707         xs << xml::EndTag("programlisting")
708            << xml::CR()
709            << xml::EndTag("textobject")
710            << xml::CR();
711
712         xs << xml::EndTag("mediaobject");
713 }
714
715
716 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
717 {
718         InsetLayout const &il = getLayout();
719         OutputParams runparams = rp;
720
721         // In some cases, the input parameters must be overridden for outer tags.
722         bool writeOuterTag = opts & WriteOuterTag;
723         if (writeOuterTag) {
724                 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
725                 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
726                         auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
727                         auto parSize = (size_t) par.size();
728                         return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
729                 });
730                 writeOuterTag = !allBibitems;
731         }
732
733         // Detect arguments that should be output before/after the paragraph.
734         // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
735         // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
736         std::set<InsetArgument const *> prependedArguments;
737         for (auto const & par : paragraphs()) {
738                 for (pos_type i = 0; i < par.size(); ++i) {
739                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
740                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
741                                 if (arg->docbookargumentbeforemaintag())
742                                         prependedArguments.insert(par.getInset(i)->asInsetArgument());
743                         }
744                 }
745         }
746
747         std::set<InsetArgument const *> appendedArguments;
748         for (auto const & par : paragraphs()) {
749                 for (pos_type i = 0; i < par.size(); ++i) {
750                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
751                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
752                                 if (arg->docbookargumentaftermaintag())
753                                         appendedArguments.insert(par.getInset(i)->asInsetArgument());
754                         }
755                 }
756         }
757
758         // Start outputting this inset.
759         // - First, wrapper around the inset and its main tag.
760         if (writeOuterTag) {
761                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
762                         xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
763
764                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
765                         docstring attrs = docstring();
766                         if (!il.docbookattr().empty())
767                                 attrs += from_ascii(il.docbookattr());
768                         if (il.docbooktag() == "link")
769                                 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
770                         xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
771                 }
772
773                 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
774                         xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
775         }
776
777         // - Think about the arguments before the paragraph.
778         OutputParams np = runparams;
779         np.docbook_in_par = true;
780         for (auto const & arg : prependedArguments)
781                 arg->docbook(xs, np);
782
783         // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
784         runparams.docbook_prepended_arguments = std::move(prependedArguments);
785         runparams.docbook_appended_arguments = appendedArguments;
786
787         // - Deal with the first item.
788         // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
789         if (writeOuterTag) {
790                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
791                         xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
792
793                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
794                         xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
795         }
796
797         // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
798
799         // With respect to XHTML, paragraphs are still allowed here.
800         if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
801                 runparams.docbook_make_pars = false;
802         if (il.isPassThru())
803                 runparams.pass_thru = true;
804
805         // - Write the main content of the inset.
806         xs.startDivision(false);
807         docbookParagraphs(text_, buffer(), xs, runparams);
808         xs.endDivision();
809
810         // - Think about the arguments after the paragraph.
811         for (auto const & arg : appendedArguments)
812                 arg->docbook(xs, np);
813
814         // - Close the required tags.
815         if (writeOuterTag) {
816                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
817                         xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
818
819                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
820                         xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
821
822                 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
823                         xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
824
825                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
826                         xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
827
828                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
829                         xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
830         }
831 }
832
833
834 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
835 {
836         return insetAsXHTML(xs, runparams, WriteEverything);
837 }
838
839
840 // FIXME XHTML
841 // There are cases where we may need to close open fonts and such
842 // and then re-open them when we are done. This would be the case, e.g.,
843 // if we were otherwise about to write:
844 //              <em>word <div class='foot'>footnote text.</div> emph</em>
845 // The problem isn't so much that the footnote text will get emphasized:
846 // we can handle that with CSS. The problem is that this is invalid XHTML.
847 // One solution would be to make the footnote <span>, but the problem is
848 // completely general, and so we'd have to make absolutely everything into
849 // span. What I think will work is to check if we're about to write "div" and,
850 // if so, try to close fonts, etc.
851 // There are probably limits to how well we can do here, though, and we will
852 // have to rely upon users not putting footnotes inside noun-type insets.
853 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
854                                   XHTMLOptions opts) const
855 {
856         // we will always want to output all our paragraphs when we are
857         // called this way.
858         OutputParams runparams = rp;
859         runparams.par_begin = 0;
860         runparams.par_end = text().paragraphs().size();
861
862         if (undefined()) {
863                 xs.startDivision(false);
864                 xhtmlParagraphs(text_, buffer(), xs, runparams);
865                 xs.endDivision();
866                 return docstring();
867         }
868
869         InsetLayout const & il = getLayout();
870         if (opts & WriteOuterTag)
871                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
872
873         if ((opts & WriteLabel) && !il.counter().empty()) {
874                 BufferParams const & bp = buffer().masterBuffer()->params();
875                 Counters & cntrs = bp.documentClass().counters();
876                 cntrs.step(il.counter(), OutputUpdate);
877                 // FIXME: translate to paragraph language
878                 if (!il.htmllabel().empty()) {
879                         docstring const lbl =
880                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
881                         // FIXME is this check necessary?
882                         if (!lbl.empty()) {
883                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
884                                 xs << lbl;
885                                 xs << xml::EndTag(il.htmllabeltag());
886                         }
887                 }
888         }
889
890         if (opts & WriteInnerTag)
891                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
892
893         // we will eventually lose information about the containing inset
894         if (!allowMultiPar() || opts == JustText)
895                 runparams.html_make_pars = false;
896         if (il.isPassThru())
897                 runparams.pass_thru = true;
898
899         xs.startDivision(false);
900         xhtmlParagraphs(text_, buffer(), xs, runparams);
901         xs.endDivision();
902
903         if (opts & WriteInnerTag)
904                 xs << xml::EndTag(il.htmlinnertag());
905
906         if (opts & WriteOuterTag)
907                 xs << xml::EndTag(il.htmltag());
908
909         return docstring();
910 }
911
912
913 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
914                         bool const post) const
915 {
916         OutputParams runparams = runparams_in;
917         runparams.local_font =
918                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
919         if (isPassThru())
920                 runparams.pass_thru = true;
921         if (post)
922                 latexArgInsetsForParent(paragraphs(), os, runparams,
923                                         getLayout().postcommandargs(), "post:");
924         else
925                 latexArgInsetsForParent(paragraphs(), os, runparams,
926                                         getLayout().latexargs());
927 }
928
929
930 void InsetText::cursorPos(BufferView const & bv,
931                 CursorSlice const & sl, bool boundary, int & x, int & y) const
932 {
933         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
934         y = bv.textMetrics(&text_).cursorY(sl, boundary);
935 }
936
937
938 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
939 {
940         clear();
941         Paragraph & first = paragraphs().front();
942         for (unsigned int i = 0; i < data.length(); ++i)
943                 first.insertChar(i, data[i], font, trackChanges);
944 }
945
946
947 void InsetText::setDrawFrame(bool flag)
948 {
949         drawFrame_ = flag;
950 }
951
952
953 ColorCode InsetText::frameColor() const
954 {
955         return frame_color_;
956 }
957
958
959 void InsetText::setFrameColor(ColorCode col)
960 {
961         frame_color_ = col;
962 }
963
964
965 void InsetText::appendParagraphs(ParagraphList & plist)
966 {
967         // There is little we can do here to keep track of changes.
968         // As of 2006/10/20, appendParagraphs is used exclusively by
969         // LyXTabular::setMultiColumn. In this context, the paragraph break
970         // is lost irreversibly and the appended text doesn't really change
971
972         ParagraphList & pl = paragraphs();
973
974         ParagraphList::iterator pit = plist.begin();
975         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
976         ++pit;
977         mergeParagraph(buffer().params(), pl,
978                        distance(pl.begin(), ins) - 1);
979
980         ParagraphList::iterator const pend = plist.end();
981         for (; pit != pend; ++pit)
982                 pl.push_back(*pit);
983 }
984
985
986 void InsetText::addPreview(DocIterator const & text_inset_pos,
987         graphics::PreviewLoader & loader) const
988 {
989         ParagraphList::const_iterator pit = paragraphs().begin();
990         ParagraphList::const_iterator pend = paragraphs().end();
991         int pidx = 0;
992
993         DocIterator inset_pos = text_inset_pos;
994         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
995
996         for (; pit != pend; ++pit, ++pidx) {
997                 InsetList::const_iterator it  = pit->insetList().begin();
998                 InsetList::const_iterator end = pit->insetList().end();
999                 inset_pos.pit() = pidx;
1000                 for (; it != end; ++it) {
1001                         inset_pos.pos() = it->pos;
1002                         it->inset->addPreview(inset_pos, loader);
1003                 }
1004         }
1005 }
1006
1007
1008 ParagraphList const & InsetText::paragraphs() const
1009 {
1010         return text_.paragraphs();
1011 }
1012
1013
1014 ParagraphList & InsetText::paragraphs()
1015 {
1016         return text_.paragraphs();
1017 }
1018
1019
1020 bool InsetText::hasCProtectContent(bool fragile) const
1021 {
1022         fragile |= getLayout().isNeedProtect();
1023         ParagraphList const & pars = paragraphs();
1024         pit_type pend = pit_type(paragraphs().size());
1025         for (pit_type pit = 0; pit != pend; ++pit) {
1026                 Paragraph const & par = pars[size_type(pit)];
1027                 if (par.needsCProtection(fragile))
1028                         return true;
1029         }
1030         return false;
1031 }
1032
1033
1034 bool InsetText::insetAllowed(InsetCode code) const
1035 {
1036         switch (code) {
1037         // Arguments, (plain) quotes and counter insets 
1038         // are also allowed in PassThru insets
1039         case ARG_CODE:
1040         case QUOTE_CODE:
1041         case COUNTER_CODE:
1042                 return true;
1043         default:
1044                 return !isPassThru();
1045         }
1046 }
1047
1048
1049 bool InsetText::allowSpellCheck() const
1050 {
1051         return getLayout().spellcheck() && !getLayout().isPassThru();
1052 }
1053
1054
1055 bool InsetText::allowMultiPar() const
1056 {
1057         return getLayout().isMultiPar();
1058 }
1059
1060
1061 bool InsetText::forcePlainLayout(idx_type) const
1062 {
1063         return getLayout().forcePlainLayout();
1064 }
1065
1066
1067 bool InsetText::allowParagraphCustomization(idx_type) const
1068 {
1069         return getLayout().allowParagraphCustomization();
1070 }
1071
1072
1073 bool InsetText::forceLocalFontSwitch() const
1074 {
1075         return getLayout().forceLocalFontSwitch();
1076 }
1077
1078
1079 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1080 {
1081         ParIterator it2 = it;
1082         it2.forwardPos();
1083         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1084         if (producesOutput()) {
1085                 InsetLayout const & il = getLayout();
1086                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1087                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1088                 if (save_layouts) {
1089                         // LYXERR0("Entering " << name());
1090                         cnt.clearLastLayout();
1091                         // FIXME cnt.saveLastCounter()?
1092                 }
1093                 buffer().updateBuffer(it2, utype, deleted);
1094                 if (save_layouts) {
1095                         // LYXERR0("Exiting " << name());
1096                         cnt.restoreLastLayout();
1097                         // FIXME cnt.restoreLastCounter()?
1098                 }
1099                 // Record if this inset is embedded in a title layout
1100                 // This is needed to decide when \maketitle is output.
1101                 intitle_context_ = it.paragraph().layout().intitle;
1102                 // Also check embedding layouts
1103                 size_t const n = it.depth();
1104                 for (size_t i = 0; i < n; ++i) {
1105                         if (it[i].paragraph().layout().intitle) {
1106                                 intitle_context_ = true;
1107                                 break;
1108                         }
1109                 }
1110         } else {
1111                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1112                 // Note that we do not need to call:
1113                 //      tclass.counters().clearLastLayout()
1114                 // since we are saving and restoring the existing counters, etc.
1115                 Counters savecnt = tclass.counters();
1116                 tclass.counters().reset();
1117                 // we need float information even in note insets (#9760)
1118                 tclass.counters().current_float(savecnt.current_float());
1119                 tclass.counters().isSubfloat(savecnt.isSubfloat());
1120                 buffer().updateBuffer(it2, utype, deleted);
1121                 tclass.counters() = std::move(savecnt);
1122         }
1123 }
1124
1125
1126 void InsetText::toString(odocstream & os) const
1127 {
1128         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1129 }
1130
1131
1132 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1133                                                         bool const shorten) const
1134 {
1135         if (!getLayout().isInToc())
1136                 return;
1137         text().forOutliner(os, maxlen, shorten);
1138 }
1139
1140
1141 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1142                                                  UpdateType utype, TocBackend & backend) const
1143 {
1144         DocIterator dit = cdit;
1145         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1146         iterateForToc(dit, output_active, utype, backend);
1147 }
1148
1149
1150 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1151                                                           UpdateType utype, TocBackend & backend) const
1152 {
1153         DocIterator dit = cdit;
1154         // This also ensures that any document has a table of contents
1155         shared_ptr<Toc> toc = backend.toc("tableofcontents");
1156
1157         BufferParams const & bufparams = buffer_->params();
1158         int const min_toclevel = bufparams.documentClass().min_toclevel();
1159         // we really should have done this before we got here, but it
1160         // can't hurt too much to do it again
1161         bool const doing_output = output_active && producesOutput();
1162
1163         // For each paragraph,
1164         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1165         //   paragraphs as needed.
1166         // * Traverse its insets and let them add their toc items
1167         // * Compute the main table of contents (this is hardcoded)
1168         // * Add the list of changes
1169         ParagraphList const & pars = paragraphs();
1170         pit_type pend = paragraphs().size();
1171         // Record pairs {start,end} of where a toc item was opened for a paragraph
1172         // and where it must be closed
1173         stack<pair<pit_type, pit_type>> addtotoc_stack;
1174
1175         for (pit_type pit = 0; pit != pend; ++pit) {
1176                 Paragraph const & par = pars[pit];
1177                 dit.pit() = pit;
1178                 dit.pos() = 0;
1179
1180                 // Custom AddToToc in paragraph layouts (i.e. theorems)
1181                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1182                         pit_type end =
1183                                 openAddToTocForParagraph(pit, dit, output_active, backend);
1184                         addtotoc_stack.push({pit, end});
1185                 }
1186
1187                 // If we find an InsetArgument that is supposed to provide the TOC caption,
1188                 // we'll save it for use later.
1189                 InsetArgument const * arginset = nullptr;
1190                 for (auto const & table : par.insetList()) {
1191                         dit.pos() = table.pos;
1192                         table.inset->addToToc(dit, doing_output, utype, backend);
1193                         if (InsetArgument const * x = table.inset->asInsetArgument())
1194                                 if (x->isTocCaption())
1195                                         arginset = x;
1196                 }
1197
1198                 // End custom AddToToc in paragraph layouts
1199                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1200                         // execute the closing function
1201                         closeAddToTocForParagraph(addtotoc_stack.top().first,
1202                                                   addtotoc_stack.top().second, backend);
1203                         addtotoc_stack.pop();
1204                 }
1205
1206                 // now the toc entry for the paragraph in the main table of contents
1207                 int const toclevel = text().getTocLevel(pit);
1208                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1209                         // insert this into the table of contents
1210                         docstring tocstring;
1211                         int const length = (doing_output && utype == OutputUpdate) ?
1212                                 INT_MAX : TOC_ENTRY_LENGTH;
1213                         if (arginset) {
1214                                 tocstring = par.labelString();
1215                                 if (!tocstring.empty())
1216                                         tocstring += ' ';
1217                                 arginset->text().forOutliner(tocstring, length);
1218                         } else
1219                                 par.forOutliner(tocstring, length);
1220                         dit.pos() = 0;
1221                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1222                                                tocstring, doing_output));
1223                 }
1224
1225                 // And now the list of changes.
1226                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1227         }
1228 }
1229
1230
1231 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1232                                              DocIterator const & dit,
1233                                              bool output_active,
1234                                              TocBackend & backend) const
1235 {
1236         Paragraph const & par = paragraphs()[pit];
1237         TocBuilder & b = backend.builder(par.layout().tocType());
1238         docstring const & label = par.labelString();
1239         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1240         return text().lastInSequence(pit);
1241 }
1242
1243
1244 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1245                                           TocBackend & backend) const
1246 {
1247         Paragraph const & par = paragraphs()[start];
1248         TocBuilder & b = backend.builder(par.layout().tocType());
1249         if (par.layout().isTocCaption()) {
1250                 docstring str;
1251                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1252                 b.argumentItem(str);
1253         }
1254         b.pop();
1255 }
1256
1257
1258 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1259 {
1260         if (buffer().isClean())
1261                 return Inset::notifyCursorLeaves(old, cur);
1262
1263         // find text inset in old cursor
1264         Cursor insetCur = old;
1265         int scriptSlice = insetCur.find(this);
1266         // we can try to continue here. returning true means
1267         // the cursor is "now" invalid. which it was.
1268         LASSERT(scriptSlice != -1, return true);
1269         insetCur.cutOff(scriptSlice);
1270         LASSERT(&insetCur.inset() == this, return true);
1271
1272         // update the old paragraph's words
1273         insetCur.paragraph().updateWords();
1274
1275         return Inset::notifyCursorLeaves(old, cur);
1276 }
1277
1278
1279 bool InsetText::completionSupported(Cursor const & cur) const
1280 {
1281         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1282         return text_.completionSupported(cur);
1283 }
1284
1285
1286 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1287 {
1288         return completionSupported(cur);
1289 }
1290
1291
1292 bool InsetText::automaticInlineCompletion() const
1293 {
1294         return lyxrc.completion_inline_text;
1295 }
1296
1297
1298 bool InsetText::automaticPopupCompletion() const
1299 {
1300         return lyxrc.completion_popup_text;
1301 }
1302
1303
1304 bool InsetText::showCompletionCursor() const
1305 {
1306         return lyxrc.completion_cursor_text &&
1307                 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1308 }
1309
1310
1311 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1312 {
1313         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1314 }
1315
1316
1317 docstring InsetText::completionPrefix(Cursor const & cur) const
1318 {
1319         if (!completionSupported(cur))
1320                 return docstring();
1321         return text_.completionPrefix(cur);
1322 }
1323
1324
1325 bool InsetText::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1326 {
1327         if (!completionSupported(cur))
1328                 return false;
1329
1330         return text_.insertCompletion(cur, s);
1331 }
1332
1333
1334 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1335         Dimension & dim) const
1336 {
1337         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1338         tm.completionPosAndDim(cur, x, y, dim);
1339 }
1340
1341
1342 string InsetText::contextMenu(BufferView const &, int, int) const
1343 {
1344         string context_menu = contextMenuName();
1345         if (context_menu != InsetText::contextMenuName())
1346                 context_menu += ";" + InsetText::contextMenuName();
1347         return context_menu;
1348 }
1349
1350
1351 string InsetText::contextMenuName() const
1352 {
1353         return "context-edit";
1354 }
1355
1356
1357 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1358 {
1359         OutputParams rp(&buffer().params().encoding());
1360         rp.for_tooltip = true;
1361         odocstringstream oss;
1362         oss << prefix;
1363
1364         ParagraphList::const_iterator beg = paragraphs().begin();
1365         ParagraphList::const_iterator end = paragraphs().end();
1366         ParagraphList::const_iterator it = beg;
1367         bool ref_printed = false;
1368
1369         for (; it != end; ++it) {
1370                 if (it != beg)
1371                         oss << '\n';
1372                 if ((*it).isRTL(buffer().params()))
1373                         oss << "<div dir=\"rtl\">";
1374                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1375                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1376                         break;
1377         }
1378         docstring str = oss.str();
1379         if (isChanged())
1380                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1381         support::truncateWithEllipsis(str, len);
1382         return str;
1383 }
1384
1385
1386 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1387 {
1388         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1389 }
1390
1391
1392 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1393 {
1394         // Nested cprotect content needs \cprotect
1395         // on each level
1396         if (producesOutput() && hasCProtectContent(fragile))
1397                 return true;
1398
1399         // Environments generally need cprotection in fragile context
1400         if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1401                 return true;
1402
1403         if (!getLayout().needsCProtect())
1404                 return false;
1405
1406         // Environments and "no latex" types (e.g., knitr chunks)
1407         // need cprotection regardless the content
1408         if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1409                 return true;
1410
1411         // If the inset does not produce output (e.g. Note or Branch),
1412         // we can ignore the contained paragraphs
1413         if (!producesOutput())
1414                 return false;
1415
1416         // Commands need cprotection if they contain specific chars
1417         int const nchars_escape = 9;
1418         static char_type const chars_escape[nchars_escape] = {
1419                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1420
1421         ParagraphList const & pars = paragraphs();
1422         pit_type pend = pit_type(paragraphs().size());
1423
1424         for (pit_type pit = 0; pit != pend; ++pit) {
1425                 Paragraph const & par = pars[size_type(pit)];
1426                 if (par.needsCProtection(fragile))
1427                         return true;
1428                 docstring const par_str = par.asString();
1429                 for (int k = 0; k < nchars_escape; k++) {
1430                         if (contains(par_str, chars_escape[k]))
1431                                 return true;
1432                 }
1433         }
1434         return false;
1435 }
1436
1437 } // namespace lyx