]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Use nullptr
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetArgument.h"
16 #include "insets/InsetLayout.h"
17
18 #include "buffer_funcs.h"
19 #include "Buffer.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "CompletionList.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "InsetList.h"
31 #include "Intl.h"
32 #include "Language.h"
33 #include "Layout.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "lyxfind.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_plaintext.h"
42 #include "output_xhtml.h"
43 #include "OutputParams.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Row.h"
48 #include "TexRow.h"
49 #include "texstream.h"
50 #include "TextClass.h"
51 #include "Text.h"
52 #include "TextMetrics.h"
53 #include "TocBackend.h"
54 #include "TocBuilder.h"
55
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
58
59 #include "support/convert.h"
60 #include "support/debug.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/RefChanger.h"
65
66 #include <algorithm>
67 #include <stack>
68
69
70 using namespace std;
71 using namespace lyx::support;
72
73
74 namespace lyx {
75
76 using graphics::PreviewLoader;
77
78
79 /////////////////////////////////////////////////////////////////////
80
81 InsetText::InsetText(Buffer * buf, UsePlain type)
82         : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
83           frame_color_(Color_insetframe),
84         text_(this, type == DefaultLayout)
85 {
86 }
87
88
89 InsetText::InsetText(InsetText const & in)
90         : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
91           intitle_context_(false), frame_color_(in.frame_color_),
92           text_(this, in.text_)
93 {
94 }
95
96
97 void InsetText::setBuffer(Buffer & buf)
98 {
99         ParagraphList::iterator end = paragraphs().end();
100         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
101                 it->setInsetBuffers(buf);
102         Inset::setBuffer(buf);
103 }
104
105
106 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
107 {
108         text_.setMacrocontextPosition(pos);
109
110         ParagraphList::const_iterator pit = paragraphs().begin();
111         ParagraphList::const_iterator pend = paragraphs().end();
112         for (; pit != pend; ++pit) {
113                 InsetList::const_iterator iit = pit->insetList().begin();
114                 InsetList::const_iterator end = pit->insetList().end();
115                 for (; iit != end; ++iit) {
116                         if (InsetText * txt = iit->inset->asInsetText()) {
117                                 DocIterator ppos(pos);
118                                 ppos.push_back(CursorSlice(*txt));
119                                 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
120                         }
121                 }
122         }
123 }
124
125
126 void InsetText::clear()
127 {
128         ParagraphList & pars = paragraphs();
129         LBUFERR(!pars.empty());
130
131         // This is a gross hack...
132         Layout const & old_layout = pars.begin()->layout();
133
134         pars.clear();
135         pars.push_back(Paragraph());
136         pars.begin()->setInsetOwner(this);
137         pars.begin()->setLayout(old_layout);
138 }
139
140
141 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
142 {
143         TextMetrics const & tm = bv.textMetrics(&text_);
144         Dimension dim = tm.dim();
145         dim.wid += leftOffset(&bv) + rightOffset(&bv);
146         dim.des += bottomOffset(&bv);
147         dim.asc += topOffset(&bv);
148         return dim;
149 }
150
151
152 void InsetText::write(ostream & os) const
153 {
154         os << "Text\n";
155         text_.write(os);
156 }
157
158
159 void InsetText::read(Lexer & lex)
160 {
161         clear();
162
163         // delete the initial paragraph
164         Paragraph oldpar = *paragraphs().begin();
165         paragraphs().clear();
166         ErrorList errorList;
167         lex.setContext("InsetText::read");
168         bool res = text_.read(lex, errorList, this);
169
170         if (!res)
171                 lex.printError("Missing \\end_inset at this point. ");
172
173         // sanity check
174         // ensure we have at least one paragraph.
175         if (paragraphs().empty())
176                 paragraphs().push_back(oldpar);
177         // Force default font, if so requested
178         // This avoids paragraphs in buffer language that would have a
179         // foreign language after a document language change, and it ensures
180         // that all new text in ERT and similar gets the "latex" language,
181         // since new text inherits the language from the last position of the
182         // existing text.  As a side effect this makes us also robust against
183         // bugs in LyX that might lead to font changes in ERT in .lyx files.
184         fixParagraphsFont();
185 }
186
187
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 {
190         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191
192         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193
194         int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
195
196         // Hand font through to contained lyxtext:
197         tm.font_.fontInfo() = mi.base.font;
198         mi.base.textwidth -= horiz_offset;
199
200         // This can happen when a layout has a left and right margin,
201         // and the view is made very narrow. We can't do better than
202         // to draw it partly out of view (bug 5890).
203         if (mi.base.textwidth < 1)
204                 mi.base.textwidth = 1;
205
206         if (hasFixedWidth())
207                 tm.metrics(mi, dim, mi.base.textwidth);
208         else
209                 tm.metrics(mi, dim);
210         mi.base.textwidth += horiz_offset;
211         dim.asc += topOffset(mi.base.bv);
212         dim.des += bottomOffset(mi.base.bv);
213         dim.wid += horiz_offset;
214 }
215
216
217 void InsetText::draw(PainterInfo & pi, int x, int y) const
218 {
219         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
220
221         int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
222         int const w = tm.width() + (horiz_offset - horiz_offset / 2);
223         int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
224         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
225         int const xframe = x + leftOffset(pi.base.bv) / 2;
226         bool change_drawn = false;
227         if (pi.full_repaint)
228                         pi.pain.fillRectangle(xframe, yframe, w, h,
229                                 pi.backgroundColor(this));
230
231         {
232                 Changer dummy = make_change(pi.background_color,
233                                             pi.backgroundColor(this, false));
234                 // The change tracking cue must not be inherited
235                 Changer dummy2 = make_change(pi.change, Change());
236                 tm.draw(pi, x + leftOffset(pi.base.bv), y);
237         }
238
239         if (drawFrame_) {
240                 // Change color of the frame in tracked changes, like for tabulars.
241                 // Only do so if the color is not custom. But do so even if RowPainter
242                 // handles the strike-through already.
243                 Color c;
244                 if (pi.change.changed()
245                     // Originally, these are the colors with role Text, from role() in
246                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
247                     // types, and also maybe it need not match in the future.
248                     && (frameColor() == Color_foreground
249                         || frameColor() == Color_cursor
250                         || frameColor() == Color_preview
251                         || frameColor() == Color_tabularline
252                         || frameColor() == Color_previewframe)) {
253                         c = pi.change.color();
254                         change_drawn = true;
255                 } else
256                         c = frameColor();
257                 pi.pain.rectangle(xframe, yframe, w, h, c);
258         }
259
260         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
261                 // Do not draw the change tracking cue if already done by RowPainter and
262                 // do not draw the cue for INSERTED if the information is already in the
263                 // color of the frame
264                 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
265 }
266
267
268 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
269 {
270         pit_type const pit = front ? 0 : paragraphs().size() - 1;
271         pos_type pos = front ? 0 : paragraphs().back().size();
272
273         // if visual information is not to be ignored, move to extreme right/left
274         if (entry_from != ENTRY_DIRECTION_IGNORE) {
275                 Cursor temp_cur = cur;
276                 temp_cur.pit() = pit;
277                 temp_cur.pos() = pos;
278                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
279                 pos = temp_cur.pos();
280         }
281
282         cur.top().setPitPos(pit, pos);
283         cur.finishUndo();
284 }
285
286
287 Inset * InsetText::editXY(Cursor & cur, int x, int y)
288 {
289         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
290 }
291
292
293 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
294 {
295         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
296
297         // See bug #9042, for instance.
298         if (isPassThru()) {
299                 // Force any new text to latex_language FIXME: This
300                 // should only be necessary in constructor, but new
301                 // paragraphs that are created by pressing enter at
302                 // the start of an existing paragraph get the buffer
303                 // language and not latex_language, so we take this
304                 // brute force approach.
305                 cur.current_font.setLanguage(latex_language);
306                 cur.real_current_font.setLanguage(latex_language);
307         }
308
309         switch (cmd.action()) {
310         case LFUN_PASTE:
311         case LFUN_CLIPBOARD_PASTE:
312         case LFUN_SELECTION_PASTE:
313         case LFUN_PRIMARY_SELECTION_PASTE:
314                 text_.dispatch(cur, cmd);
315                 // If we we can only store plain text, we must reset all
316                 // attributes.
317                 // FIXME: Change only the pasted paragraphs
318                 fixParagraphsFont();
319                 break;
320
321         case LFUN_INSET_DISSOLVE: {
322                 bool const main_inset = text_.isMainText();
323                 bool const target_inset = cmd.argument().empty()
324                         || cmd.getArg(0) == insetName(lyxCode());
325
326                 if (!main_inset && target_inset) {
327                         // Text::dissolveInset assumes that the cursor
328                         // is inside the Inset.
329                         if (&cur.inset() != this)
330                                 cur.pushBackward(*this);
331                         cur.beginUndoGroup();
332                         text_.dispatch(cur, cmd);
333                         cur.endUndoGroup();
334                 } else
335                         cur.undispatched();
336                 break;
337         }
338
339         default:
340                 text_.dispatch(cur, cmd);
341         }
342
343         if (!cur.result().dispatched())
344                 Inset::doDispatch(cur, cmd);
345 }
346
347
348 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
349         FuncStatus & status) const
350 {
351         switch (cmd.action()) {
352         case LFUN_INSET_DISSOLVE: {
353                 bool const main_inset = text_.isMainText();
354                 bool const target_inset = cmd.argument().empty()
355                         || cmd.getArg(0) == insetName(lyxCode());
356
357                 if (target_inset)
358                         status.setEnabled(!main_inset);
359                 return target_inset;
360         }
361
362         case LFUN_ARGUMENT_INSERT: {
363                 string const arg = cmd.getArg(0);
364                 if (arg.empty()) {
365                         status.setEnabled(false);
366                         return true;
367                 }
368                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
369                         return text_.getStatus(cur, cmd, status);
370
371                 Layout::LaTeXArgMap args = getLayout().args();
372                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
373                 if (lait != args.end()) {
374                         status.setEnabled(true);
375                         for (Paragraph const & par : paragraphs())
376                                 for (auto const & table : par.insetList())
377                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
378                                                 if (ins->name() == arg) {
379                                                         // we have this already
380                                                         status.setEnabled(false);
381                                                         return true;
382                                                 }
383                 } else
384                         status.setEnabled(false);
385                 return true;
386         }
387
388         default:
389                 // Dispatch only to text_ if the cursor is inside
390                 // the text_. It is not for context menus (bug 5797).
391                 bool ret = false;
392                 if (cur.text() == &text_)
393                         ret = text_.getStatus(cur, cmd, status);
394
395                 if (!ret)
396                         ret = Inset::getStatus(cur, cmd, status);
397                 return ret;
398         }
399 }
400
401
402 void InsetText::fixParagraphsFont()
403 {
404         Font font(inherit_font, buffer().params().language);
405         font.setLanguage(latex_language);
406         ParagraphList::iterator par = paragraphs().begin();
407         ParagraphList::iterator const end = paragraphs().end();
408         while (par != end) {
409                 if (par->isPassThru())
410                         par->resetFonts(font);
411                 if (!par->allowParagraphCustomization())
412                         par->params().clear();
413                 ++par;
414         }
415 }
416
417
418 // bool InsetText::isChanged() const
419 // {
420 //      ParagraphList::const_iterator pit = paragraphs().begin();
421 //      ParagraphList::const_iterator end = paragraphs().end();
422 //      for (; pit != end; ++pit) {
423 //              if (pit->isChanged())
424 //                      return true;
425 //      }
426 //      return false;
427 // }
428
429
430 void InsetText::setChange(Change const & change)
431 {
432         ParagraphList::iterator pit = paragraphs().begin();
433         ParagraphList::iterator end = paragraphs().end();
434         for (; pit != end; ++pit) {
435                 pit->setChange(change);
436         }
437 }
438
439
440 void InsetText::acceptChanges()
441 {
442         text_.acceptChanges();
443 }
444
445
446 void InsetText::rejectChanges()
447 {
448         text_.rejectChanges();
449 }
450
451
452 void InsetText::validate(LaTeXFeatures & features) const
453 {
454         features.useInsetLayout(getLayout());
455         for (Paragraph const & p : paragraphs())
456                 p.validate(features);
457 }
458
459
460 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
461 {
462         // This implements the standard way of handling the LaTeX
463         // output of a text inset, either a command or an
464         // environment. Standard collapsible insets should not
465         // redefine this, non-standard ones may call this.
466         InsetLayout const & il = getLayout();
467         if (il.forceOwnlines())
468                 os << breakln;
469         bool needendgroup = false;
470         if (!il.latexname().empty()) {
471                 if (il.latextype() == InsetLayout::COMMAND) {
472                         // FIXME UNICODE
473                         // FIXME \protect should only be used for fragile
474                         //    commands, but we do not provide this information yet.
475                         if (hasCProtectContent(runparams.moving_arg)) {
476                                 if (contains(runparams.active_chars, '^')) {
477                                         // cprotect relies on ^ being on catcode 7
478                                         os << "\\begingroup\\catcode`\\^=7";
479                                         needendgroup = true;
480                                 }
481                                 os << "\\cprotect";
482                         } else if (runparams.moving_arg)
483                                 os << "\\protect";
484                         os << '\\' << from_utf8(il.latexname());
485                         if (!il.latexargs().empty())
486                                 getArgs(os, runparams);
487                         if (!il.latexparam().empty())
488                                 os << from_utf8(il.latexparam());
489                         os << '{';
490                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
491                         if (il.isDisplay())
492                                 os << breakln;
493                         else
494                                 os << safebreakln;
495                         if (runparams.lastid != -1)
496                                 os.texrow().start(runparams.lastid,
497                                                   runparams.lastpos);
498                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
499                         if (!il.latexargs().empty())
500                                 getArgs(os, runparams);
501                         if (!il.latexparam().empty())
502                                 os << from_utf8(il.latexparam());
503                         os << '\n';
504                 }
505         } else {
506                 if (!il.latexargs().empty())
507                         getArgs(os, runparams);
508                 if (!il.latexparam().empty())
509                         os << from_utf8(il.latexparam());
510         }
511
512         if (!il.leftdelim().empty())
513                 os << il.leftdelim();
514
515         OutputParams rp = runparams;
516         if (isPassThru())
517                 rp.pass_thru = true;
518         if (il.isNeedProtect())
519                 rp.moving_arg = true;
520         if (il.isNeedMBoxProtect())
521                 ++rp.inulemcmd;
522         if (!il.passThruChars().empty())
523                 rp.pass_thru_chars += il.passThruChars();
524         if (!il.newlineCmd().empty())
525                 rp.newlinecmd = il.newlineCmd();
526         rp.par_begin = 0;
527         rp.par_end = paragraphs().size();
528
529         // Output the contents of the inset
530         latexParagraphs(buffer(), text_, os, rp);
531         runparams.encoding = rp.encoding;
532         // Pass the post_macros upstream
533         runparams.post_macro = rp.post_macro;
534         // These need to be passed upstream as well
535         runparams.need_maketitle = rp.need_maketitle;
536         runparams.have_maketitle = rp.have_maketitle;
537
538         if (!il.rightdelim().empty())
539                 os << il.rightdelim();
540
541         if (!il.latexname().empty()) {
542                 if (il.latextype() == InsetLayout::COMMAND) {
543                         os << "}";
544                         if (!il.postcommandargs().empty())
545                                 getArgs(os, runparams, true);
546                         if (needendgroup)
547                                 os << "\\endgroup";
548                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
549                         // A comment environment doesn't need a % before \n\end
550                         if (il.isDisplay() || runparams.inComment)
551                                 os << breakln;
552                         else
553                                 os << safebreakln;
554                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
555                         if (!il.isDisplay())
556                                 os.protectSpace(true);
557                 }
558         }
559         if (il.forceOwnlines())
560                 os << breakln;
561 }
562
563
564 int InsetText::plaintext(odocstringstream & os,
565         OutputParams const & runparams, size_t max_length) const
566 {
567         ParagraphList::const_iterator beg = paragraphs().begin();
568         ParagraphList::const_iterator end = paragraphs().end();
569         ParagraphList::const_iterator it = beg;
570         bool ref_printed = false;
571         int len = 0;
572         for (; it != end; ++it) {
573                 if (it != beg) {
574                         os << '\n';
575                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
576                                 os << '\n';
577                 }
578                 odocstringstream oss;
579                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
580                 docstring const str = oss.str();
581                 os << str;
582                 // FIXME: len is not computed fully correctly; in principle,
583                 // we have to count the characters after the last '\n'
584                 len = str.size();
585                 if (os.str().size() >= max_length)
586                         break;
587         }
588
589         return len;
590 }
591
592
593
594 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
595 {
596         docbook(xs, rp, WriteEverything);
597 }
598
599
600 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
601 {
602         // we will always want to output all our paragraphs when we are
603         // called this way.
604         OutputParams runparams = rp;
605         runparams.par_begin = 0;
606         runparams.par_end = text().paragraphs().size();
607
608         if (undefined()) {
609                 xs.startDivision(false);
610                 docbookParagraphs(text_, buffer(), xs, runparams);
611                 xs.endDivision();
612                 return;
613         }
614
615         InsetLayout const & il = getLayout();
616         if (opts & WriteOuterTag && !il.docbooktag().empty() && il.docbooktag() != "NONE") {
617                 docstring attrs = docstring();
618                 if (!il.docbookattr().empty())
619                         attrs += from_ascii(il.docbookattr());
620                 if (il.docbooktag() == "link")
621                         attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
622                 xs << xml::StartTag(il.docbooktag(), attrs);
623         }
624
625         // No need for labels that are generated from counters.
626
627         // With respect to XHTML, paragraphs are still allowed here.
628         if (!allowMultiPar())
629                 runparams.docbook_make_pars = false;
630         if (il.isPassThru())
631                 runparams.pass_thru = true;
632
633         xs.startDivision(false);
634         docbookParagraphs(text_, buffer(), xs, runparams);
635         xs.endDivision();
636
637         if (opts & WriteOuterTag)
638                 xs << xml::EndTag(il.docbooktag());
639 }
640
641
642 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
643 {
644         return insetAsXHTML(xs, runparams, WriteEverything);
645 }
646
647
648 // FIXME XHTML
649 // There are cases where we may need to close open fonts and such
650 // and then re-open them when we are done. This would be the case, e.g.,
651 // if we were otherwise about to write:
652 //              <em>word <div class='foot'>footnote text.</div> emph</em>
653 // The problem isn't so much that the footnote text will get emphasized:
654 // we can handle that with CSS. The problem is that this is invalid XHTML.
655 // One solution would be to make the footnote <span>, but the problem is
656 // completely general, and so we'd have to make absolutely everything into
657 // span. What I think will work is to check if we're about to write "div" and,
658 // if so, try to close fonts, etc.
659 // There are probably limits to how well we can do here, though, and we will
660 // have to rely upon users not putting footnotes inside noun-type insets.
661 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
662                                   XHTMLOptions opts) const
663 {
664         // we will always want to output all our paragraphs when we are
665         // called this way.
666         OutputParams runparams = rp;
667         runparams.par_begin = 0;
668         runparams.par_end = text().paragraphs().size();
669
670         if (undefined()) {
671                 xs.startDivision(false);
672                 xhtmlParagraphs(text_, buffer(), xs, runparams);
673                 xs.endDivision();
674                 return docstring();
675         }
676
677         InsetLayout const & il = getLayout();
678         if (opts & WriteOuterTag)
679                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
680
681         if ((opts & WriteLabel) && !il.counter().empty()) {
682                 BufferParams const & bp = buffer().masterBuffer()->params();
683                 Counters & cntrs = bp.documentClass().counters();
684                 cntrs.step(il.counter(), OutputUpdate);
685                 // FIXME: translate to paragraph language
686                 if (!il.htmllabel().empty()) {
687                         docstring const lbl =
688                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
689                         // FIXME is this check necessary?
690                         if (!lbl.empty()) {
691                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
692                                 xs << lbl;
693                                 xs << xml::EndTag(il.htmllabeltag());
694                         }
695                 }
696         }
697
698         if (opts & WriteInnerTag)
699                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
700
701         // we will eventually lose information about the containing inset
702         if (!allowMultiPar() || opts == JustText)
703                 runparams.html_make_pars = false;
704         if (il.isPassThru())
705                 runparams.pass_thru = true;
706
707         xs.startDivision(false);
708         xhtmlParagraphs(text_, buffer(), xs, runparams);
709         xs.endDivision();
710
711         if (opts & WriteInnerTag)
712                 xs << xml::EndTag(il.htmlinnertag());
713
714         if (opts & WriteOuterTag)
715                 xs << xml::EndTag(il.htmltag());
716
717         return docstring();
718 }
719
720
721 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
722                         bool const post) const
723 {
724         OutputParams runparams = runparams_in;
725         runparams.local_font =
726                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
727         if (isPassThru())
728                 runparams.pass_thru = true;
729         if (post)
730                 latexArgInsetsForParent(paragraphs(), os, runparams,
731                                         getLayout().postcommandargs(), "post:");
732         else
733                 latexArgInsetsForParent(paragraphs(), os, runparams,
734                                         getLayout().latexargs());
735 }
736
737
738 void InsetText::cursorPos(BufferView const & bv,
739                 CursorSlice const & sl, bool boundary, int & x, int & y) const
740 {
741         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
742         y = bv.textMetrics(&text_).cursorY(sl, boundary);
743 }
744
745
746 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
747 {
748         clear();
749         Paragraph & first = paragraphs().front();
750         for (unsigned int i = 0; i < data.length(); ++i)
751                 first.insertChar(i, data[i], font, trackChanges);
752 }
753
754
755 void InsetText::setDrawFrame(bool flag)
756 {
757         drawFrame_ = flag;
758 }
759
760
761 ColorCode InsetText::frameColor() const
762 {
763         return frame_color_;
764 }
765
766
767 void InsetText::setFrameColor(ColorCode col)
768 {
769         frame_color_ = col;
770 }
771
772
773 void InsetText::appendParagraphs(ParagraphList & plist)
774 {
775         // There is little we can do here to keep track of changes.
776         // As of 2006/10/20, appendParagraphs is used exclusively by
777         // LyXTabular::setMultiColumn. In this context, the paragraph break
778         // is lost irreversibly and the appended text doesn't really change
779
780         ParagraphList & pl = paragraphs();
781
782         ParagraphList::iterator pit = plist.begin();
783         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
784         ++pit;
785         mergeParagraph(buffer().params(), pl,
786                        distance(pl.begin(), ins) - 1);
787
788         ParagraphList::iterator const pend = plist.end();
789         for (; pit != pend; ++pit)
790                 pl.push_back(*pit);
791 }
792
793
794 void InsetText::addPreview(DocIterator const & text_inset_pos,
795         PreviewLoader & loader) const
796 {
797         ParagraphList::const_iterator pit = paragraphs().begin();
798         ParagraphList::const_iterator pend = paragraphs().end();
799         int pidx = 0;
800
801         DocIterator inset_pos = text_inset_pos;
802         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
803
804         for (; pit != pend; ++pit, ++pidx) {
805                 InsetList::const_iterator it  = pit->insetList().begin();
806                 InsetList::const_iterator end = pit->insetList().end();
807                 inset_pos.pit() = pidx;
808                 for (; it != end; ++it) {
809                         inset_pos.pos() = it->pos;
810                         it->inset->addPreview(inset_pos, loader);
811                 }
812         }
813 }
814
815
816 ParagraphList const & InsetText::paragraphs() const
817 {
818         return text_.paragraphs();
819 }
820
821
822 ParagraphList & InsetText::paragraphs()
823 {
824         return text_.paragraphs();
825 }
826
827
828 bool InsetText::hasCProtectContent(bool fragile) const
829 {
830         fragile |= getLayout().isNeedProtect();
831         ParagraphList const & pars = paragraphs();
832         pit_type pend = pit_type(paragraphs().size());
833         for (pit_type pit = 0; pit != pend; ++pit) {
834                 Paragraph const & par = pars[size_type(pit)];
835                 if (par.needsCProtection(fragile))
836                         return true;
837         }
838         return false;
839 }
840
841
842 bool InsetText::insetAllowed(InsetCode code) const
843 {
844         switch (code) {
845         // Arguments and (plain) quotes are also allowed in PassThru insets
846         case ARG_CODE:
847         case QUOTE_CODE:
848                 return true;
849         default:
850                 return !isPassThru();
851         }
852 }
853
854
855 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
856 {
857         ParIterator it2 = it;
858         it2.forwardPos();
859         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
860         if (producesOutput()) {
861                 InsetLayout const & il = getLayout();
862                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
863                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
864                 if (save_layouts) {
865                         // LYXERR0("Entering " << name());
866                         cnt.clearLastLayout();
867                         // FIXME cnt.saveLastCounter()?
868                 }
869                 buffer().updateBuffer(it2, utype, deleted);
870                 if (save_layouts) {
871                         // LYXERR0("Exiting " << name());
872                         cnt.restoreLastLayout();
873                         // FIXME cnt.restoreLastCounter()?
874                 }
875                 // Record in this inset is embedded in a title layout
876                 // This is needed to decide when \maketitle is output.
877                 intitle_context_ = it.paragraph().layout().intitle;
878                 // Also check embedding layouts
879                 size_t const n = it.depth();
880                 for (size_t i = 0; i < n; ++i) {
881                         if (it[i].paragraph().layout().intitle) {
882                                 intitle_context_ = true;
883                                 break;
884                         }
885                 }
886         } else {
887                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
888                 // Note that we do not need to call:
889                 //      tclass.counters().clearLastLayout()
890                 // since we are saving and restoring the existing counters, etc.
891                 Counters savecnt = tclass.counters();
892                 tclass.counters().reset();
893                 // we need float information even in note insets (#9760)
894                 tclass.counters().current_float(savecnt.current_float());
895                 tclass.counters().isSubfloat(savecnt.isSubfloat());
896                 buffer().updateBuffer(it2, utype, deleted);
897                 tclass.counters() = move(savecnt);
898         }
899 }
900
901
902 void InsetText::toString(odocstream & os) const
903 {
904         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
905 }
906
907
908 void InsetText::forOutliner(docstring & os, size_t const maxlen,
909                                                         bool const shorten) const
910 {
911         if (!getLayout().isInToc())
912                 return;
913         text().forOutliner(os, maxlen, shorten);
914 }
915
916
917 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
918                                                  UpdateType utype, TocBackend & backend) const
919 {
920         DocIterator dit = cdit;
921         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
922         iterateForToc(dit, output_active, utype, backend);
923 }
924
925
926 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
927                                                           UpdateType utype, TocBackend & backend) const
928 {
929         DocIterator dit = cdit;
930         // This also ensures that any document has a table of contents
931         shared_ptr<Toc> toc = backend.toc("tableofcontents");
932
933         BufferParams const & bufparams = buffer_->params();
934         int const min_toclevel = bufparams.documentClass().min_toclevel();
935         // we really should have done this before we got here, but it
936         // can't hurt too much to do it again
937         bool const doing_output = output_active && producesOutput();
938
939         // For each paragraph,
940         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
941         //   paragraphs as needed.
942         // * Traverse its insets and let them add their toc items
943         // * Compute the main table of contents (this is hardcoded)
944         // * Add the list of changes
945         ParagraphList const & pars = paragraphs();
946         pit_type pend = paragraphs().size();
947         // Record pairs {start,end} of where a toc item was opened for a paragraph
948         // and where it must be closed
949         stack<pair<pit_type, pit_type>> addtotoc_stack;
950
951         for (pit_type pit = 0; pit != pend; ++pit) {
952                 Paragraph const & par = pars[pit];
953                 dit.pit() = pit;
954                 dit.pos() = 0;
955
956                 // Custom AddToToc in paragraph layouts (i.e. theorems)
957                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
958                         pit_type end =
959                                 openAddToTocForParagraph(pit, dit, output_active, backend);
960                         addtotoc_stack.push({pit, end});
961                 }
962
963                 // If we find an InsetArgument that is supposed to provide the TOC caption,
964                 // we'll save it for use later.
965                 InsetArgument const * arginset = nullptr;
966                 for (auto const & table : par.insetList()) {
967                         dit.pos() = table.pos;
968                         table.inset->addToToc(dit, doing_output, utype, backend);
969                         if (InsetArgument const * x = table.inset->asInsetArgument())
970                                 if (x->isTocCaption())
971                                         arginset = x;
972                 }
973
974                 // End custom AddToToc in paragraph layouts
975                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
976                         // execute the closing function
977                         closeAddToTocForParagraph(addtotoc_stack.top().first,
978                                                   addtotoc_stack.top().second, backend);
979                         addtotoc_stack.pop();
980                 }
981
982                 // now the toc entry for the paragraph in the main table of contents
983                 int const toclevel = text().getTocLevel(pit);
984                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
985                         // insert this into the table of contents
986                         docstring tocstring;
987                         int const length = (doing_output && utype == OutputUpdate) ?
988                                 INT_MAX : TOC_ENTRY_LENGTH;
989                         if (arginset) {
990                                 tocstring = par.labelString();
991                                 if (!tocstring.empty())
992                                         tocstring += ' ';
993                                 arginset->text().forOutliner(tocstring, length);
994                         } else
995                                 par.forOutliner(tocstring, length);
996                         dit.pos() = 0;
997                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
998                                                tocstring, doing_output));
999                 }
1000
1001                 // And now the list of changes.
1002                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1003         }
1004 }
1005
1006
1007 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1008                                              DocIterator const & dit,
1009                                              bool output_active,
1010                                              TocBackend & backend) const
1011 {
1012         Paragraph const & par = paragraphs()[pit];
1013         TocBuilder & b = backend.builder(par.layout().tocType());
1014         docstring const label = par.labelString();
1015         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1016         return text().lastInSequence(pit);
1017 }
1018
1019
1020 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1021                                           TocBackend & backend) const
1022 {
1023         Paragraph const & par = paragraphs()[start];
1024         TocBuilder & b = backend.builder(par.layout().tocType());
1025         if (par.layout().isTocCaption()) {
1026                 docstring str;
1027                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1028                 b.argumentItem(str);
1029         }
1030         b.pop();
1031 }
1032
1033
1034 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1035 {
1036         if (buffer().isClean())
1037                 return Inset::notifyCursorLeaves(old, cur);
1038
1039         // find text inset in old cursor
1040         Cursor insetCur = old;
1041         int scriptSlice = insetCur.find(this);
1042         // we can try to continue here. returning true means
1043         // the cursor is "now" invalid. which it was.
1044         LASSERT(scriptSlice != -1, return true);
1045         insetCur.cutOff(scriptSlice);
1046         LASSERT(&insetCur.inset() == this, return true);
1047
1048         // update the old paragraph's words
1049         insetCur.paragraph().updateWords();
1050
1051         return Inset::notifyCursorLeaves(old, cur);
1052 }
1053
1054
1055 bool InsetText::completionSupported(Cursor const & cur) const
1056 {
1057         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1058         return text_.completionSupported(cur);
1059 }
1060
1061
1062 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1063 {
1064         return completionSupported(cur);
1065 }
1066
1067
1068 bool InsetText::automaticInlineCompletion() const
1069 {
1070         return lyxrc.completion_inline_text;
1071 }
1072
1073
1074 bool InsetText::automaticPopupCompletion() const
1075 {
1076         return lyxrc.completion_popup_text;
1077 }
1078
1079
1080 bool InsetText::showCompletionCursor() const
1081 {
1082         return lyxrc.completion_cursor_text;
1083 }
1084
1085
1086 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1087 {
1088         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1089 }
1090
1091
1092 docstring InsetText::completionPrefix(Cursor const & cur) const
1093 {
1094         if (!completionSupported(cur))
1095                 return docstring();
1096         return text_.completionPrefix(cur);
1097 }
1098
1099
1100 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1101         bool finished)
1102 {
1103         if (!completionSupported(cur))
1104                 return false;
1105
1106         return text_.insertCompletion(cur, s, finished);
1107 }
1108
1109
1110 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1111         Dimension & dim) const
1112 {
1113         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1114         tm.completionPosAndDim(cur, x, y, dim);
1115 }
1116
1117
1118 string InsetText::contextMenu(BufferView const &, int, int) const
1119 {
1120         string context_menu = contextMenuName();
1121         if (context_menu != InsetText::contextMenuName())
1122                 context_menu += ";" + InsetText::contextMenuName();
1123         return context_menu;
1124 }
1125
1126
1127 string InsetText::contextMenuName() const
1128 {
1129         return "context-edit";
1130 }
1131
1132
1133 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1134 {
1135         OutputParams rp(&buffer().params().encoding());
1136         rp.for_tooltip = true;
1137         odocstringstream oss;
1138         oss << prefix;
1139
1140         ParagraphList::const_iterator beg = paragraphs().begin();
1141         ParagraphList::const_iterator end = paragraphs().end();
1142         ParagraphList::const_iterator it = beg;
1143         bool ref_printed = false;
1144
1145         for (; it != end; ++it) {
1146                 if (it != beg)
1147                         oss << '\n';
1148                 if ((*it).isRTL(buffer().params()))
1149                         oss << "<div dir=\"rtl\">";
1150                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1151                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1152                         break;
1153         }
1154         docstring str = oss.str();
1155         if (isChanged())
1156                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1157         support::truncateWithEllipsis(str, len);
1158         return str;
1159 }
1160
1161
1162 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1163 {
1164         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1165 }
1166
1167
1168 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1169 {
1170         // Nested cprotect content needs \cprotect
1171         // on each level
1172         if (producesOutput() && hasCProtectContent(fragile))
1173                 return true;
1174
1175         // Environments generally need cprotection in fragile context
1176         if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1177                 return true;
1178
1179         if (!getLayout().needsCProtect())
1180                 return false;
1181
1182         // Environments and "no latex" types (e.g., knitr chunks)
1183         // need cprotection regardless the content
1184         if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1185                 return true;
1186
1187         // If the inset does not produce output (e.g. Note or Branch),
1188         // we can ignore the contained paragraphs
1189         if (!producesOutput())
1190                 return false;
1191
1192         // Commands need cprotection if they contain specific chars
1193         int const nchars_escape = 9;
1194         static char_type const chars_escape[nchars_escape] = {
1195                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1196
1197         ParagraphList const & pars = paragraphs();
1198         pit_type pend = pit_type(paragraphs().size());
1199
1200         for (pit_type pit = 0; pit != pend; ++pit) {
1201                 Paragraph const & par = pars[size_type(pit)];
1202                 if (par.needsCProtection(fragile))
1203                         return true;
1204                 docstring const par_str = par.asString();
1205                 for (int k = 0; k < nchars_escape; k++) {
1206                         if (contains(par_str, chars_escape[k]))
1207                                 return true;
1208                 }
1209         }
1210         return false;
1211 }
1212
1213 } // namespace lyx