]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Fixup aeb51be9: set current font correctly when editing inset
[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 "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.setCurrentFont();
284         cur.finishUndo();
285 }
286
287
288 Inset * InsetText::editXY(Cursor & cur, int x, int y)
289 {
290         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
291 }
292
293
294 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
295 {
296         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
297
298 #if 0
299         // See bug #9042, for instance.
300         if (isPassThru()) {
301                 // Force any new text to latex_language FIXME: This
302                 // should only be necessary in constructor, but new
303                 // paragraphs that are created by pressing enter at
304                 // the start of an existing paragraph get the buffer
305                 // language and not latex_language, so we take this
306                 // brute force approach.
307                 cur.current_font.setLanguage(latex_language);
308                 cur.real_current_font.setLanguage(latex_language);
309         }
310 #endif
311
312         switch (cmd.action()) {
313         case LFUN_PASTE:
314         case LFUN_CLIPBOARD_PASTE:
315         case LFUN_SELECTION_PASTE:
316         case LFUN_PRIMARY_SELECTION_PASTE:
317                 text_.dispatch(cur, cmd);
318                 // If we we can only store plain text, we must reset all
319                 // attributes.
320                 // FIXME: Change only the pasted paragraphs
321                 fixParagraphsFont();
322                 break;
323
324         case LFUN_INSET_DISSOLVE: {
325                 bool const main_inset = text_.isMainText();
326                 bool const target_inset = cmd.argument().empty()
327                         || cmd.getArg(0) == insetName(lyxCode());
328
329                 if (!main_inset && target_inset) {
330                         // Text::dissolveInset assumes that the cursor
331                         // is inside the Inset.
332                         if (&cur.inset() != this)
333                                 cur.pushBackward(*this);
334                         cur.beginUndoGroup();
335                         text_.dispatch(cur, cmd);
336                         cur.endUndoGroup();
337                 } else
338                         cur.undispatched();
339                 break;
340         }
341
342         default:
343                 text_.dispatch(cur, cmd);
344         }
345
346         if (!cur.result().dispatched())
347                 Inset::doDispatch(cur, cmd);
348 }
349
350
351 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
352         FuncStatus & status) const
353 {
354         switch (cmd.action()) {
355         case LFUN_INSET_DISSOLVE: {
356                 bool const main_inset = text_.isMainText();
357                 bool const target_inset = cmd.argument().empty()
358                         || cmd.getArg(0) == insetName(lyxCode());
359
360                 if (target_inset)
361                         status.setEnabled(!main_inset);
362                 return target_inset;
363         }
364
365         case LFUN_ARGUMENT_INSERT: {
366                 string const arg = cmd.getArg(0);
367                 if (arg.empty()) {
368                         status.setEnabled(false);
369                         return true;
370                 }
371                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
372                         return text_.getStatus(cur, cmd, status);
373
374                 Layout::LaTeXArgMap args = getLayout().args();
375                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
376                 if (lait != args.end()) {
377                         status.setEnabled(true);
378                         for (Paragraph const & par : paragraphs())
379                                 for (auto const & table : par.insetList())
380                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
381                                                 if (ins->name() == arg) {
382                                                         // we have this already
383                                                         status.setEnabled(false);
384                                                         return true;
385                                                 }
386                 } else
387                         status.setEnabled(false);
388                 return true;
389         }
390
391         default:
392                 // Dispatch only to text_ if the cursor is inside
393                 // the text_. It is not for context menus (bug 5797).
394                 bool ret = false;
395                 if (cur.text() == &text_)
396                         ret = text_.getStatus(cur, cmd, status);
397
398                 if (!ret)
399                         ret = Inset::getStatus(cur, cmd, status);
400                 return ret;
401         }
402 }
403
404
405 void InsetText::fixParagraphsFont()
406 {
407         Font font(inherit_font, buffer().params().language);
408         font.setLanguage(latex_language);
409         ParagraphList::iterator par = paragraphs().begin();
410         ParagraphList::iterator const end = paragraphs().end();
411         while (par != end) {
412                 if (par->isPassThru())
413                         par->resetFonts(font);
414                 if (!par->allowParagraphCustomization())
415                         par->params().clear();
416                 ++par;
417         }
418 }
419
420
421 // bool InsetText::isChanged() const
422 // {
423 //      ParagraphList::const_iterator pit = paragraphs().begin();
424 //      ParagraphList::const_iterator end = paragraphs().end();
425 //      for (; pit != end; ++pit) {
426 //              if (pit->isChanged())
427 //                      return true;
428 //      }
429 //      return false;
430 // }
431
432
433 void InsetText::setChange(Change const & change)
434 {
435         ParagraphList::iterator pit = paragraphs().begin();
436         ParagraphList::iterator end = paragraphs().end();
437         for (; pit != end; ++pit) {
438                 pit->setChange(change);
439         }
440 }
441
442
443 void InsetText::acceptChanges()
444 {
445         text_.acceptChanges();
446 }
447
448
449 void InsetText::rejectChanges()
450 {
451         text_.rejectChanges();
452 }
453
454
455 void InsetText::validate(LaTeXFeatures & features) const
456 {
457         features.useInsetLayout(getLayout());
458         for (Paragraph const & p : paragraphs())
459                 p.validate(features);
460 }
461
462
463 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
464 {
465         // This implements the standard way of handling the LaTeX
466         // output of a text inset, either a command or an
467         // environment. Standard collapsible insets should not
468         // redefine this, non-standard ones may call this.
469         InsetLayout const & il = getLayout();
470         if (il.forceOwnlines())
471                 os << breakln;
472         bool needendgroup = false;
473         if (!il.latexname().empty()) {
474                 if (il.latextype() == InsetLayout::COMMAND) {
475                         // FIXME UNICODE
476                         // FIXME \protect should only be used for fragile
477                         //    commands, but we do not provide this information yet.
478                         if (hasCProtectContent(runparams.moving_arg)) {
479                                 if (contains(runparams.active_chars, '^')) {
480                                         // cprotect relies on ^ being on catcode 7
481                                         os << "\\begingroup\\catcode`\\^=7";
482                                         needendgroup = true;
483                                 }
484                                 os << "\\cprotect";
485                         } else if (runparams.moving_arg)
486                                 os << "\\protect";
487                         os << '\\' << from_utf8(il.latexname());
488                         if (!il.latexargs().empty())
489                                 getArgs(os, runparams);
490                         if (!il.latexparam().empty())
491                                 os << from_utf8(il.latexparam());
492                         os << '{';
493                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
494                         if (il.isDisplay())
495                                 os << breakln;
496                         else
497                                 os << safebreakln;
498                         if (runparams.lastid != -1)
499                                 os.texrow().start(runparams.lastid,
500                                                   runparams.lastpos);
501                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
502                         if (!il.latexargs().empty())
503                                 getArgs(os, runparams);
504                         if (!il.latexparam().empty())
505                                 os << from_utf8(il.latexparam());
506                         os << '\n';
507                 }
508         } else {
509                 if (!il.latexargs().empty())
510                         getArgs(os, runparams);
511                 if (!il.latexparam().empty())
512                         os << from_utf8(il.latexparam());
513         }
514
515         if (!il.leftdelim().empty())
516                 os << il.leftdelim();
517
518         OutputParams rp = runparams;
519         if (isPassThru())
520                 rp.pass_thru = true;
521         if (il.isNeedProtect())
522                 rp.moving_arg = true;
523         if (il.isNeedMBoxProtect())
524                 ++rp.inulemcmd;
525         if (!il.passThruChars().empty())
526                 rp.pass_thru_chars += il.passThruChars();
527         if (!il.newlineCmd().empty())
528                 rp.newlinecmd = il.newlineCmd();
529         rp.par_begin = 0;
530         rp.par_end = paragraphs().size();
531
532         // Output the contents of the inset
533         latexParagraphs(buffer(), text_, os, rp);
534         runparams.encoding = rp.encoding;
535         // Pass the post_macros upstream
536         runparams.post_macro = rp.post_macro;
537         // These need to be passed upstream as well
538         runparams.need_maketitle = rp.need_maketitle;
539         runparams.have_maketitle = rp.have_maketitle;
540
541         if (!il.rightdelim().empty())
542                 os << il.rightdelim();
543
544         if (!il.latexname().empty()) {
545                 if (il.latextype() == InsetLayout::COMMAND) {
546                         os << "}";
547                         if (!il.postcommandargs().empty())
548                                 getArgs(os, runparams, true);
549                         if (needendgroup)
550                                 os << "\\endgroup";
551                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
552                         // A comment environment doesn't need a % before \n\end
553                         if (il.isDisplay() || runparams.inComment)
554                                 os << breakln;
555                         else
556                                 os << safebreakln;
557                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
558                         if (!il.isDisplay())
559                                 os.protectSpace(true);
560                 }
561         }
562         if (il.forceOwnlines())
563                 os << breakln;
564 }
565
566
567 int InsetText::plaintext(odocstringstream & os,
568         OutputParams const & runparams, size_t max_length) const
569 {
570         ParagraphList::const_iterator beg = paragraphs().begin();
571         ParagraphList::const_iterator end = paragraphs().end();
572         ParagraphList::const_iterator it = beg;
573         bool ref_printed = false;
574         int len = 0;
575         for (; it != end; ++it) {
576                 if (it != beg) {
577                         os << '\n';
578                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
579                                 os << '\n';
580                 }
581                 odocstringstream oss;
582                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
583                 docstring const str = oss.str();
584                 os << str;
585                 // FIXME: len is not computed fully correctly; in principle,
586                 // we have to count the characters after the last '\n'
587                 len = str.size();
588                 if (os.str().size() >= max_length)
589                         break;
590         }
591
592         return len;
593 }
594
595
596
597 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
598 {
599         docbook(xs, rp, WriteEverything);
600 }
601
602
603 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
604 {
605         // we will always want to output all our paragraphs when we are
606         // called this way.
607         OutputParams runparams = rp;
608         runparams.par_begin = 0;
609         runparams.par_end = text().paragraphs().size();
610
611         if (undefined()) {
612                 xs.startDivision(false);
613                 docbookParagraphs(text_, buffer(), xs, runparams);
614                 xs.endDivision();
615                 return;
616         }
617
618         InsetLayout const & il = getLayout();
619         if (opts & WriteOuterTag && !il.docbooktag().empty() && il.docbooktag() != "NONE") {
620                 docstring attrs = docstring();
621                 if (!il.docbookattr().empty())
622                         attrs += from_ascii(il.docbookattr());
623                 if (il.docbooktag() == "link")
624                         attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
625                 xs << xml::StartTag(il.docbooktag(), attrs);
626         }
627
628         // No need for labels that are generated from counters.
629
630         // With respect to XHTML, paragraphs are still allowed here.
631         if (!allowMultiPar())
632                 runparams.docbook_make_pars = false;
633         if (il.isPassThru())
634                 runparams.pass_thru = true;
635
636         xs.startDivision(false);
637         docbookParagraphs(text_, buffer(), xs, runparams);
638         xs.endDivision();
639
640         if (opts & WriteOuterTag)
641                 xs << xml::EndTag(il.docbooktag());
642 }
643
644
645 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
646 {
647         return insetAsXHTML(xs, runparams, WriteEverything);
648 }
649
650
651 // FIXME XHTML
652 // There are cases where we may need to close open fonts and such
653 // and then re-open them when we are done. This would be the case, e.g.,
654 // if we were otherwise about to write:
655 //              <em>word <div class='foot'>footnote text.</div> emph</em>
656 // The problem isn't so much that the footnote text will get emphasized:
657 // we can handle that with CSS. The problem is that this is invalid XHTML.
658 // One solution would be to make the footnote <span>, but the problem is
659 // completely general, and so we'd have to make absolutely everything into
660 // span. What I think will work is to check if we're about to write "div" and,
661 // if so, try to close fonts, etc.
662 // There are probably limits to how well we can do here, though, and we will
663 // have to rely upon users not putting footnotes inside noun-type insets.
664 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
665                                   XHTMLOptions opts) const
666 {
667         // we will always want to output all our paragraphs when we are
668         // called this way.
669         OutputParams runparams = rp;
670         runparams.par_begin = 0;
671         runparams.par_end = text().paragraphs().size();
672
673         if (undefined()) {
674                 xs.startDivision(false);
675                 xhtmlParagraphs(text_, buffer(), xs, runparams);
676                 xs.endDivision();
677                 return docstring();
678         }
679
680         InsetLayout const & il = getLayout();
681         if (opts & WriteOuterTag)
682                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
683
684         if ((opts & WriteLabel) && !il.counter().empty()) {
685                 BufferParams const & bp = buffer().masterBuffer()->params();
686                 Counters & cntrs = bp.documentClass().counters();
687                 cntrs.step(il.counter(), OutputUpdate);
688                 // FIXME: translate to paragraph language
689                 if (!il.htmllabel().empty()) {
690                         docstring const lbl =
691                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
692                         // FIXME is this check necessary?
693                         if (!lbl.empty()) {
694                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
695                                 xs << lbl;
696                                 xs << xml::EndTag(il.htmllabeltag());
697                         }
698                 }
699         }
700
701         if (opts & WriteInnerTag)
702                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
703
704         // we will eventually lose information about the containing inset
705         if (!allowMultiPar() || opts == JustText)
706                 runparams.html_make_pars = false;
707         if (il.isPassThru())
708                 runparams.pass_thru = true;
709
710         xs.startDivision(false);
711         xhtmlParagraphs(text_, buffer(), xs, runparams);
712         xs.endDivision();
713
714         if (opts & WriteInnerTag)
715                 xs << xml::EndTag(il.htmlinnertag());
716
717         if (opts & WriteOuterTag)
718                 xs << xml::EndTag(il.htmltag());
719
720         return docstring();
721 }
722
723
724 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
725                         bool const post) const
726 {
727         OutputParams runparams = runparams_in;
728         runparams.local_font =
729                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
730         if (isPassThru())
731                 runparams.pass_thru = true;
732         if (post)
733                 latexArgInsetsForParent(paragraphs(), os, runparams,
734                                         getLayout().postcommandargs(), "post:");
735         else
736                 latexArgInsetsForParent(paragraphs(), os, runparams,
737                                         getLayout().latexargs());
738 }
739
740
741 void InsetText::cursorPos(BufferView const & bv,
742                 CursorSlice const & sl, bool boundary, int & x, int & y) const
743 {
744         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
745         y = bv.textMetrics(&text_).cursorY(sl, boundary);
746 }
747
748
749 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
750 {
751         clear();
752         Paragraph & first = paragraphs().front();
753         for (unsigned int i = 0; i < data.length(); ++i)
754                 first.insertChar(i, data[i], font, trackChanges);
755 }
756
757
758 void InsetText::setDrawFrame(bool flag)
759 {
760         drawFrame_ = flag;
761 }
762
763
764 ColorCode InsetText::frameColor() const
765 {
766         return frame_color_;
767 }
768
769
770 void InsetText::setFrameColor(ColorCode col)
771 {
772         frame_color_ = col;
773 }
774
775
776 void InsetText::appendParagraphs(ParagraphList & plist)
777 {
778         // There is little we can do here to keep track of changes.
779         // As of 2006/10/20, appendParagraphs is used exclusively by
780         // LyXTabular::setMultiColumn. In this context, the paragraph break
781         // is lost irreversibly and the appended text doesn't really change
782
783         ParagraphList & pl = paragraphs();
784
785         ParagraphList::iterator pit = plist.begin();
786         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
787         ++pit;
788         mergeParagraph(buffer().params(), pl,
789                        distance(pl.begin(), ins) - 1);
790
791         ParagraphList::iterator const pend = plist.end();
792         for (; pit != pend; ++pit)
793                 pl.push_back(*pit);
794 }
795
796
797 void InsetText::addPreview(DocIterator const & text_inset_pos,
798         PreviewLoader & loader) const
799 {
800         ParagraphList::const_iterator pit = paragraphs().begin();
801         ParagraphList::const_iterator pend = paragraphs().end();
802         int pidx = 0;
803
804         DocIterator inset_pos = text_inset_pos;
805         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
806
807         for (; pit != pend; ++pit, ++pidx) {
808                 InsetList::const_iterator it  = pit->insetList().begin();
809                 InsetList::const_iterator end = pit->insetList().end();
810                 inset_pos.pit() = pidx;
811                 for (; it != end; ++it) {
812                         inset_pos.pos() = it->pos;
813                         it->inset->addPreview(inset_pos, loader);
814                 }
815         }
816 }
817
818
819 ParagraphList const & InsetText::paragraphs() const
820 {
821         return text_.paragraphs();
822 }
823
824
825 ParagraphList & InsetText::paragraphs()
826 {
827         return text_.paragraphs();
828 }
829
830
831 bool InsetText::hasCProtectContent(bool fragile) const
832 {
833         fragile |= getLayout().isNeedProtect();
834         ParagraphList const & pars = paragraphs();
835         pit_type pend = pit_type(paragraphs().size());
836         for (pit_type pit = 0; pit != pend; ++pit) {
837                 Paragraph const & par = pars[size_type(pit)];
838                 if (par.needsCProtection(fragile))
839                         return true;
840         }
841         return false;
842 }
843
844
845 bool InsetText::insetAllowed(InsetCode code) const
846 {
847         switch (code) {
848         // Arguments and (plain) quotes are also allowed in PassThru insets
849         case ARG_CODE:
850         case QUOTE_CODE:
851                 return true;
852         default:
853                 return !isPassThru();
854         }
855 }
856
857
858 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
859 {
860         ParIterator it2 = it;
861         it2.forwardPos();
862         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
863         if (producesOutput()) {
864                 InsetLayout const & il = getLayout();
865                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
866                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
867                 if (save_layouts) {
868                         // LYXERR0("Entering " << name());
869                         cnt.clearLastLayout();
870                         // FIXME cnt.saveLastCounter()?
871                 }
872                 buffer().updateBuffer(it2, utype, deleted);
873                 if (save_layouts) {
874                         // LYXERR0("Exiting " << name());
875                         cnt.restoreLastLayout();
876                         // FIXME cnt.restoreLastCounter()?
877                 }
878                 // Record in this inset is embedded in a title layout
879                 // This is needed to decide when \maketitle is output.
880                 intitle_context_ = it.paragraph().layout().intitle;
881                 // Also check embedding layouts
882                 size_t const n = it.depth();
883                 for (size_t i = 0; i < n; ++i) {
884                         if (it[i].paragraph().layout().intitle) {
885                                 intitle_context_ = true;
886                                 break;
887                         }
888                 }
889         } else {
890                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
891                 // Note that we do not need to call:
892                 //      tclass.counters().clearLastLayout()
893                 // since we are saving and restoring the existing counters, etc.
894                 Counters savecnt = tclass.counters();
895                 tclass.counters().reset();
896                 // we need float information even in note insets (#9760)
897                 tclass.counters().current_float(savecnt.current_float());
898                 tclass.counters().isSubfloat(savecnt.isSubfloat());
899                 buffer().updateBuffer(it2, utype, deleted);
900                 tclass.counters() = move(savecnt);
901         }
902 }
903
904
905 void InsetText::toString(odocstream & os) const
906 {
907         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
908 }
909
910
911 void InsetText::forOutliner(docstring & os, size_t const maxlen,
912                                                         bool const shorten) const
913 {
914         if (!getLayout().isInToc())
915                 return;
916         text().forOutliner(os, maxlen, shorten);
917 }
918
919
920 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
921                                                  UpdateType utype, TocBackend & backend) const
922 {
923         DocIterator dit = cdit;
924         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
925         iterateForToc(dit, output_active, utype, backend);
926 }
927
928
929 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
930                                                           UpdateType utype, TocBackend & backend) const
931 {
932         DocIterator dit = cdit;
933         // This also ensures that any document has a table of contents
934         shared_ptr<Toc> toc = backend.toc("tableofcontents");
935
936         BufferParams const & bufparams = buffer_->params();
937         int const min_toclevel = bufparams.documentClass().min_toclevel();
938         // we really should have done this before we got here, but it
939         // can't hurt too much to do it again
940         bool const doing_output = output_active && producesOutput();
941
942         // For each paragraph,
943         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
944         //   paragraphs as needed.
945         // * Traverse its insets and let them add their toc items
946         // * Compute the main table of contents (this is hardcoded)
947         // * Add the list of changes
948         ParagraphList const & pars = paragraphs();
949         pit_type pend = paragraphs().size();
950         // Record pairs {start,end} of where a toc item was opened for a paragraph
951         // and where it must be closed
952         stack<pair<pit_type, pit_type>> addtotoc_stack;
953
954         for (pit_type pit = 0; pit != pend; ++pit) {
955                 Paragraph const & par = pars[pit];
956                 dit.pit() = pit;
957                 dit.pos() = 0;
958
959                 // Custom AddToToc in paragraph layouts (i.e. theorems)
960                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
961                         pit_type end =
962                                 openAddToTocForParagraph(pit, dit, output_active, backend);
963                         addtotoc_stack.push({pit, end});
964                 }
965
966                 // If we find an InsetArgument that is supposed to provide the TOC caption,
967                 // we'll save it for use later.
968                 InsetArgument const * arginset = nullptr;
969                 for (auto const & table : par.insetList()) {
970                         dit.pos() = table.pos;
971                         table.inset->addToToc(dit, doing_output, utype, backend);
972                         if (InsetArgument const * x = table.inset->asInsetArgument())
973                                 if (x->isTocCaption())
974                                         arginset = x;
975                 }
976
977                 // End custom AddToToc in paragraph layouts
978                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
979                         // execute the closing function
980                         closeAddToTocForParagraph(addtotoc_stack.top().first,
981                                                   addtotoc_stack.top().second, backend);
982                         addtotoc_stack.pop();
983                 }
984
985                 // now the toc entry for the paragraph in the main table of contents
986                 int const toclevel = text().getTocLevel(pit);
987                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
988                         // insert this into the table of contents
989                         docstring tocstring;
990                         int const length = (doing_output && utype == OutputUpdate) ?
991                                 INT_MAX : TOC_ENTRY_LENGTH;
992                         if (arginset) {
993                                 tocstring = par.labelString();
994                                 if (!tocstring.empty())
995                                         tocstring += ' ';
996                                 arginset->text().forOutliner(tocstring, length);
997                         } else
998                                 par.forOutliner(tocstring, length);
999                         dit.pos() = 0;
1000                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1001                                                tocstring, doing_output));
1002                 }
1003
1004                 // And now the list of changes.
1005                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1006         }
1007 }
1008
1009
1010 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1011                                              DocIterator const & dit,
1012                                              bool output_active,
1013                                              TocBackend & backend) const
1014 {
1015         Paragraph const & par = paragraphs()[pit];
1016         TocBuilder & b = backend.builder(par.layout().tocType());
1017         docstring const & label = par.labelString();
1018         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1019         return text().lastInSequence(pit);
1020 }
1021
1022
1023 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1024                                           TocBackend & backend) const
1025 {
1026         Paragraph const & par = paragraphs()[start];
1027         TocBuilder & b = backend.builder(par.layout().tocType());
1028         if (par.layout().isTocCaption()) {
1029                 docstring str;
1030                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1031                 b.argumentItem(str);
1032         }
1033         b.pop();
1034 }
1035
1036
1037 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1038 {
1039         if (buffer().isClean())
1040                 return Inset::notifyCursorLeaves(old, cur);
1041
1042         // find text inset in old cursor
1043         Cursor insetCur = old;
1044         int scriptSlice = insetCur.find(this);
1045         // we can try to continue here. returning true means
1046         // the cursor is "now" invalid. which it was.
1047         LASSERT(scriptSlice != -1, return true);
1048         insetCur.cutOff(scriptSlice);
1049         LASSERT(&insetCur.inset() == this, return true);
1050
1051         // update the old paragraph's words
1052         insetCur.paragraph().updateWords();
1053
1054         return Inset::notifyCursorLeaves(old, cur);
1055 }
1056
1057
1058 bool InsetText::completionSupported(Cursor const & cur) const
1059 {
1060         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1061         return text_.completionSupported(cur);
1062 }
1063
1064
1065 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1066 {
1067         return completionSupported(cur);
1068 }
1069
1070
1071 bool InsetText::automaticInlineCompletion() const
1072 {
1073         return lyxrc.completion_inline_text;
1074 }
1075
1076
1077 bool InsetText::automaticPopupCompletion() const
1078 {
1079         return lyxrc.completion_popup_text;
1080 }
1081
1082
1083 bool InsetText::showCompletionCursor() const
1084 {
1085         return lyxrc.completion_cursor_text;
1086 }
1087
1088
1089 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1090 {
1091         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1092 }
1093
1094
1095 docstring InsetText::completionPrefix(Cursor const & cur) const
1096 {
1097         if (!completionSupported(cur))
1098                 return docstring();
1099         return text_.completionPrefix(cur);
1100 }
1101
1102
1103 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1104         bool finished)
1105 {
1106         if (!completionSupported(cur))
1107                 return false;
1108
1109         return text_.insertCompletion(cur, s, finished);
1110 }
1111
1112
1113 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1114         Dimension & dim) const
1115 {
1116         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1117         tm.completionPosAndDim(cur, x, y, dim);
1118 }
1119
1120
1121 string InsetText::contextMenu(BufferView const &, int, int) const
1122 {
1123         string context_menu = contextMenuName();
1124         if (context_menu != InsetText::contextMenuName())
1125                 context_menu += ";" + InsetText::contextMenuName();
1126         return context_menu;
1127 }
1128
1129
1130 string InsetText::contextMenuName() const
1131 {
1132         return "context-edit";
1133 }
1134
1135
1136 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1137 {
1138         OutputParams rp(&buffer().params().encoding());
1139         rp.for_tooltip = true;
1140         odocstringstream oss;
1141         oss << prefix;
1142
1143         ParagraphList::const_iterator beg = paragraphs().begin();
1144         ParagraphList::const_iterator end = paragraphs().end();
1145         ParagraphList::const_iterator it = beg;
1146         bool ref_printed = false;
1147
1148         for (; it != end; ++it) {
1149                 if (it != beg)
1150                         oss << '\n';
1151                 if ((*it).isRTL(buffer().params()))
1152                         oss << "<div dir=\"rtl\">";
1153                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1154                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1155                         break;
1156         }
1157         docstring str = oss.str();
1158         if (isChanged())
1159                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1160         support::truncateWithEllipsis(str, len);
1161         return str;
1162 }
1163
1164
1165 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1166 {
1167         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1168 }
1169
1170
1171 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1172 {
1173         // Nested cprotect content needs \cprotect
1174         // on each level
1175         if (producesOutput() && hasCProtectContent(fragile))
1176                 return true;
1177
1178         // Environments generally need cprotection in fragile context
1179         if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1180                 return true;
1181
1182         if (!getLayout().needsCProtect())
1183                 return false;
1184
1185         // Environments and "no latex" types (e.g., knitr chunks)
1186         // need cprotection regardless the content
1187         if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1188                 return true;
1189
1190         // If the inset does not produce output (e.g. Note or Branch),
1191         // we can ignore the contained paragraphs
1192         if (!producesOutput())
1193                 return false;
1194
1195         // Commands need cprotection if they contain specific chars
1196         int const nchars_escape = 9;
1197         static char_type const chars_escape[nchars_escape] = {
1198                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1199
1200         ParagraphList const & pars = paragraphs();
1201         pit_type pend = pit_type(paragraphs().size());
1202
1203         for (pit_type pit = 0; pit != pend; ++pit) {
1204                 Paragraph const & par = pars[size_type(pit)];
1205                 if (par.needsCProtection(fragile))
1206                         return true;
1207                 docstring const par_str = par.asString();
1208                 for (int k = 0; k < nchars_escape; k++) {
1209                         if (contains(par_str, chars_escape[k]))
1210                                 return true;
1211                 }
1212         }
1213         return false;
1214 }
1215
1216 } // namespace lyx