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