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