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