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