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