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