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