3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetText.h"
15 #include "insets/InsetArgument.h"
16 #include "insets/InsetLayout.h"
18 #include "buffer_funcs.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "CompletionList.h"
23 #include "CoordCache.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"
34 #include "LaTeXFeatures.h"
38 #include "MetricsInfo.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_plaintext.h"
42 #include "output_xhtml.h"
43 #include "OutputParams.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "texstream.h"
50 #include "TextClass.h"
52 #include "TextMetrics.h"
53 #include "TocBackend.h"
54 #include "TocBuilder.h"
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
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"
71 using namespace lyx::support;
76 using graphics::PreviewLoader;
79 /////////////////////////////////////////////////////////////////////
81 InsetText::InsetText(Buffer * buf, UsePlain type)
82 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
83 frame_color_(Color_insetframe),
84 text_(this, type == DefaultLayout)
89 InsetText::InsetText(InsetText const & in)
90 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
91 intitle_context_(false), frame_color_(in.frame_color_),
97 void InsetText::setBuffer(Buffer & buf)
99 ParagraphList::iterator end = paragraphs().end();
100 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
101 it->setInsetBuffers(buf);
102 Inset::setBuffer(buf);
106 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
108 text_.setMacrocontextPosition(pos);
110 ParagraphList::const_iterator pit = paragraphs().begin();
111 ParagraphList::const_iterator pend = paragraphs().end();
112 for (; pit != pend; ++pit) {
113 InsetList::const_iterator iit = pit->insetList().begin();
114 InsetList::const_iterator end = pit->insetList().end();
115 for (; iit != end; ++iit) {
116 if (InsetText * txt = iit->inset->asInsetText()) {
117 DocIterator ppos(pos);
118 ppos.push_back(CursorSlice(*txt));
119 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
126 void InsetText::clear()
128 ParagraphList & pars = paragraphs();
129 LBUFERR(!pars.empty());
131 // This is a gross hack...
132 Layout const & old_layout = pars.begin()->layout();
135 pars.push_back(Paragraph());
136 pars.begin()->setInsetOwner(this);
137 pars.begin()->setLayout(old_layout);
141 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
143 TextMetrics const & tm = bv.textMetrics(&text_);
144 Dimension dim = tm.dim();
145 dim.wid += leftOffset(&bv) + rightOffset(&bv);
146 dim.des += bottomOffset(&bv);
147 dim.asc += topOffset(&bv);
152 void InsetText::write(ostream & os) const
159 void InsetText::read(Lexer & lex)
163 // delete the initial paragraph
164 Paragraph oldpar = *paragraphs().begin();
165 paragraphs().clear();
167 lex.setContext("InsetText::read");
168 bool res = text_.read(lex, errorList, this);
171 lex.printError("Missing \\end_inset at this point. ");
174 // ensure we have at least one paragraph.
175 if (paragraphs().empty())
176 paragraphs().push_back(oldpar);
177 // Force default font, if so requested
178 // This avoids paragraphs in buffer language that would have a
179 // foreign language after a document language change, and it ensures
180 // that all new text in ERT and similar gets the "latex" language,
181 // since new text inherits the language from the last position of the
182 // existing text. As a side effect this makes us also robust against
183 // bugs in LyX that might lead to font changes in ERT in .lyx files.
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
190 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
192 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
194 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
196 // Hand font through to contained lyxtext:
197 tm.font_.fontInfo() = mi.base.font;
198 mi.base.textwidth -= horiz_offset;
200 // This can happen when a layout has a left and right margin,
201 // and the view is made very narrow. We can't do better than
202 // to draw it partly out of view (bug 5890).
203 if (mi.base.textwidth < 1)
204 mi.base.textwidth = 1;
207 tm.metrics(mi, dim, mi.base.textwidth);
210 mi.base.textwidth += horiz_offset;
211 dim.asc += topOffset(mi.base.bv);
212 dim.des += bottomOffset(mi.base.bv);
213 dim.wid += horiz_offset;
217 void InsetText::draw(PainterInfo & pi, int x, int y) const
219 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
221 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
222 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
223 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
224 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
225 int const xframe = x + leftOffset(pi.base.bv) / 2;
226 bool change_drawn = false;
228 pi.pain.fillRectangle(xframe, yframe, w, h,
229 pi.backgroundColor(this));
232 Changer dummy = make_change(pi.background_color,
233 pi.backgroundColor(this, false));
234 // The change tracking cue must not be inherited
235 Changer dummy2 = make_change(pi.change, Change());
236 tm.draw(pi, x + leftOffset(pi.base.bv), y);
240 // Change color of the frame in tracked changes, like for tabulars.
241 // Only do so if the color is not custom. But do so even if RowPainter
242 // handles the strike-through already.
244 if (pi.change.changed()
245 // Originally, these are the colors with role Text, from role() in
246 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
247 // types, and also maybe it need not match in the future.
248 && (frameColor() == Color_foreground
249 || frameColor() == Color_cursor
250 || frameColor() == Color_preview
251 || frameColor() == Color_tabularline
252 || frameColor() == Color_previewframe)) {
253 c = pi.change.color();
257 pi.pain.rectangle(xframe, yframe, w, h, c);
260 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
261 // Do not draw the change tracking cue if already done by RowPainter and
262 // do not draw the cue for INSERTED if the information is already in the
263 // color of the frame
264 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
268 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
270 pit_type const pit = front ? 0 : paragraphs().size() - 1;
271 pos_type pos = front ? 0 : paragraphs().back().size();
273 // if visual information is not to be ignored, move to extreme right/left
274 if (entry_from != ENTRY_DIRECTION_IGNORE) {
275 Cursor temp_cur = cur;
276 temp_cur.pit() = pit;
277 temp_cur.pos() = pos;
278 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
279 pos = temp_cur.pos();
282 cur.top().setPitPos(pit, pos);
283 cur.setCurrentFont();
288 Inset * InsetText::editXY(Cursor & cur, int x, int y)
290 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
294 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
296 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
299 // See bug #9042, for instance.
301 // Force any new text to latex_language FIXME: This
302 // should only be necessary in constructor, but new
303 // paragraphs that are created by pressing enter at
304 // the start of an existing paragraph get the buffer
305 // language and not latex_language, so we take this
306 // brute force approach.
307 cur.current_font.setLanguage(latex_language);
308 cur.real_current_font.setLanguage(latex_language);
312 switch (cmd.action()) {
314 case LFUN_CLIPBOARD_PASTE:
315 case LFUN_SELECTION_PASTE:
316 case LFUN_PRIMARY_SELECTION_PASTE:
317 text_.dispatch(cur, cmd);
318 // If we we can only store plain text, we must reset all
320 // FIXME: Change only the pasted paragraphs
324 case LFUN_INSET_DISSOLVE: {
325 bool const main_inset = text_.isMainText();
326 bool const target_inset = cmd.argument().empty()
327 || cmd.getArg(0) == insetName(lyxCode());
329 if (!main_inset && target_inset) {
330 // Text::dissolveInset assumes that the cursor
331 // is inside the Inset.
332 if (&cur.inset() != this)
333 cur.pushBackward(*this);
334 cur.beginUndoGroup();
335 text_.dispatch(cur, cmd);
343 text_.dispatch(cur, cmd);
346 if (!cur.result().dispatched())
347 Inset::doDispatch(cur, cmd);
351 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
352 FuncStatus & status) const
354 switch (cmd.action()) {
355 case LFUN_INSET_DISSOLVE: {
356 bool const main_inset = text_.isMainText();
357 bool const target_inset = cmd.argument().empty()
358 || cmd.getArg(0) == insetName(lyxCode());
361 status.setEnabled(!main_inset);
365 case LFUN_ARGUMENT_INSERT: {
366 string const arg = cmd.getArg(0);
368 status.setEnabled(false);
371 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
372 return text_.getStatus(cur, cmd, status);
374 Layout::LaTeXArgMap args = getLayout().args();
375 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
376 if (lait != args.end()) {
377 status.setEnabled(true);
378 for (Paragraph const & par : paragraphs())
379 for (auto const & table : par.insetList())
380 if (InsetArgument const * ins = table.inset->asInsetArgument())
381 if (ins->name() == arg) {
382 // we have this already
383 status.setEnabled(false);
387 status.setEnabled(false);
392 // Dispatch only to text_ if the cursor is inside
393 // the text_. It is not for context menus (bug 5797).
395 if (cur.text() == &text_)
396 ret = text_.getStatus(cur, cmd, status);
399 ret = Inset::getStatus(cur, cmd, status);
405 void InsetText::fixParagraphsFont()
407 Font font(inherit_font, buffer().params().language);
408 font.setLanguage(latex_language);
409 ParagraphList::iterator par = paragraphs().begin();
410 ParagraphList::iterator const end = paragraphs().end();
412 if (par->isPassThru())
413 par->resetFonts(font);
414 if (!par->allowParagraphCustomization())
415 par->params().clear();
421 // bool InsetText::isChanged() const
423 // ParagraphList::const_iterator pit = paragraphs().begin();
424 // ParagraphList::const_iterator end = paragraphs().end();
425 // for (; pit != end; ++pit) {
426 // if (pit->isChanged())
433 void InsetText::setChange(Change const & change)
435 ParagraphList::iterator pit = paragraphs().begin();
436 ParagraphList::iterator end = paragraphs().end();
437 for (; pit != end; ++pit) {
438 pit->setChange(change);
443 void InsetText::acceptChanges()
445 text_.acceptChanges();
449 void InsetText::rejectChanges()
451 text_.rejectChanges();
455 void InsetText::validate(LaTeXFeatures & features) const
457 features.useInsetLayout(getLayout());
458 for (Paragraph const & p : paragraphs())
459 p.validate(features);
463 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
465 // This implements the standard way of handling the LaTeX
466 // output of a text inset, either a command or an
467 // environment. Standard collapsible insets should not
468 // redefine this, non-standard ones may call this.
469 InsetLayout const & il = getLayout();
470 if (il.forceOwnlines())
472 bool needendgroup = false;
473 if (!il.latexname().empty()) {
474 if (il.latextype() == InsetLayout::COMMAND) {
476 // FIXME \protect should only be used for fragile
477 // commands, but we do not provide this information yet.
478 if (hasCProtectContent(runparams.moving_arg)) {
479 if (contains(runparams.active_chars, '^')) {
480 // cprotect relies on ^ being on catcode 7
481 os << "\\begingroup\\catcode`\\^=7";
485 } else if (runparams.moving_arg)
487 os << '\\' << from_utf8(il.latexname());
488 if (!il.latexargs().empty())
489 getArgs(os, runparams);
490 if (!il.latexparam().empty())
491 os << from_utf8(il.latexparam());
493 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
498 if (runparams.lastid != -1)
499 os.texrow().start(runparams.lastid,
501 os << "\\begin{" << from_utf8(il.latexname()) << "}";
502 if (!il.latexargs().empty())
503 getArgs(os, runparams);
504 if (!il.latexparam().empty())
505 os << from_utf8(il.latexparam());
509 if (!il.latexargs().empty())
510 getArgs(os, runparams);
511 if (!il.latexparam().empty())
512 os << from_utf8(il.latexparam());
515 if (!il.leftdelim().empty())
516 os << il.leftdelim();
518 OutputParams rp = runparams;
521 if (il.isNeedProtect())
522 rp.moving_arg = true;
523 if (il.isNeedMBoxProtect())
525 if (!il.passThruChars().empty())
526 rp.pass_thru_chars += il.passThruChars();
527 if (!il.newlineCmd().empty())
528 rp.newlinecmd = il.newlineCmd();
530 rp.par_end = paragraphs().size();
532 // Output the contents of the inset
533 latexParagraphs(buffer(), text_, os, rp);
534 runparams.encoding = rp.encoding;
535 // Pass the post_macros upstream
536 runparams.post_macro = rp.post_macro;
537 // These need to be passed upstream as well
538 runparams.need_maketitle = rp.need_maketitle;
539 runparams.have_maketitle = rp.have_maketitle;
541 if (!il.rightdelim().empty())
542 os << il.rightdelim();
544 if (!il.latexname().empty()) {
545 if (il.latextype() == InsetLayout::COMMAND) {
547 if (!il.postcommandargs().empty())
548 getArgs(os, runparams, true);
551 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
552 // A comment environment doesn't need a % before \n\end
553 if (il.isDisplay() || runparams.inComment)
557 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
559 os.protectSpace(true);
562 if (il.forceOwnlines())
567 int InsetText::plaintext(odocstringstream & os,
568 OutputParams const & runparams, size_t max_length) const
570 ParagraphList::const_iterator beg = paragraphs().begin();
571 ParagraphList::const_iterator end = paragraphs().end();
572 ParagraphList::const_iterator it = beg;
573 bool ref_printed = false;
575 for (; it != end; ++it) {
578 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
581 odocstringstream oss;
582 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
583 docstring const str = oss.str();
585 // FIXME: len is not computed fully correctly; in principle,
586 // we have to count the characters after the last '\n'
588 if (os.str().size() >= max_length)
597 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
599 docbook(xs, rp, WriteEverything);
603 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
605 // we will always want to output all our paragraphs when we are
607 OutputParams runparams = rp;
608 runparams.par_begin = 0;
609 runparams.par_end = text().paragraphs().size();
612 xs.startDivision(false);
613 docbookParagraphs(text_, buffer(), xs, runparams);
618 InsetLayout const & il = getLayout();
619 if (opts & WriteOuterTag && !il.docbooktag().empty() && il.docbooktag() != "NONE") {
620 docstring attrs = docstring();
621 if (!il.docbookattr().empty())
622 attrs += from_ascii(il.docbookattr());
623 if (il.docbooktag() == "link")
624 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
625 xs << xml::StartTag(il.docbooktag(), attrs);
628 // No need for labels that are generated from counters.
630 // With respect to XHTML, paragraphs are still allowed here.
631 if (!allowMultiPar())
632 runparams.docbook_make_pars = false;
634 runparams.pass_thru = true;
636 xs.startDivision(false);
637 docbookParagraphs(text_, buffer(), xs, runparams);
640 if (opts & WriteOuterTag)
641 xs << xml::EndTag(il.docbooktag());
645 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
647 return insetAsXHTML(xs, runparams, WriteEverything);
652 // There are cases where we may need to close open fonts and such
653 // and then re-open them when we are done. This would be the case, e.g.,
654 // if we were otherwise about to write:
655 // <em>word <div class='foot'>footnote text.</div> emph</em>
656 // The problem isn't so much that the footnote text will get emphasized:
657 // we can handle that with CSS. The problem is that this is invalid XHTML.
658 // One solution would be to make the footnote <span>, but the problem is
659 // completely general, and so we'd have to make absolutely everything into
660 // span. What I think will work is to check if we're about to write "div" and,
661 // if so, try to close fonts, etc.
662 // There are probably limits to how well we can do here, though, and we will
663 // have to rely upon users not putting footnotes inside noun-type insets.
664 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
665 XHTMLOptions opts) const
667 // we will always want to output all our paragraphs when we are
669 OutputParams runparams = rp;
670 runparams.par_begin = 0;
671 runparams.par_end = text().paragraphs().size();
674 xs.startDivision(false);
675 xhtmlParagraphs(text_, buffer(), xs, runparams);
680 InsetLayout const & il = getLayout();
681 if (opts & WriteOuterTag)
682 xs << xml::StartTag(il.htmltag(), il.htmlattr());
684 if ((opts & WriteLabel) && !il.counter().empty()) {
685 BufferParams const & bp = buffer().masterBuffer()->params();
686 Counters & cntrs = bp.documentClass().counters();
687 cntrs.step(il.counter(), OutputUpdate);
688 // FIXME: translate to paragraph language
689 if (!il.htmllabel().empty()) {
690 docstring const lbl =
691 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
692 // FIXME is this check necessary?
694 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
696 xs << xml::EndTag(il.htmllabeltag());
701 if (opts & WriteInnerTag)
702 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
704 // we will eventually lose information about the containing inset
705 if (!allowMultiPar() || opts == JustText)
706 runparams.html_make_pars = false;
708 runparams.pass_thru = true;
710 xs.startDivision(false);
711 xhtmlParagraphs(text_, buffer(), xs, runparams);
714 if (opts & WriteInnerTag)
715 xs << xml::EndTag(il.htmlinnertag());
717 if (opts & WriteOuterTag)
718 xs << xml::EndTag(il.htmltag());
724 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
725 bool const post) const
727 OutputParams runparams = runparams_in;
728 runparams.local_font =
729 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
731 runparams.pass_thru = true;
733 latexArgInsetsForParent(paragraphs(), os, runparams,
734 getLayout().postcommandargs(), "post:");
736 latexArgInsetsForParent(paragraphs(), os, runparams,
737 getLayout().latexargs());
741 void InsetText::cursorPos(BufferView const & bv,
742 CursorSlice const & sl, bool boundary, int & x, int & y) const
744 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
745 y = bv.textMetrics(&text_).cursorY(sl, boundary);
749 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
752 Paragraph & first = paragraphs().front();
753 for (unsigned int i = 0; i < data.length(); ++i)
754 first.insertChar(i, data[i], font, trackChanges);
758 void InsetText::setDrawFrame(bool flag)
764 ColorCode InsetText::frameColor() const
770 void InsetText::setFrameColor(ColorCode col)
776 void InsetText::appendParagraphs(ParagraphList & plist)
778 // There is little we can do here to keep track of changes.
779 // As of 2006/10/20, appendParagraphs is used exclusively by
780 // LyXTabular::setMultiColumn. In this context, the paragraph break
781 // is lost irreversibly and the appended text doesn't really change
783 ParagraphList & pl = paragraphs();
785 ParagraphList::iterator pit = plist.begin();
786 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
788 mergeParagraph(buffer().params(), pl,
789 distance(pl.begin(), ins) - 1);
791 ParagraphList::iterator const pend = plist.end();
792 for (; pit != pend; ++pit)
797 void InsetText::addPreview(DocIterator const & text_inset_pos,
798 PreviewLoader & loader) const
800 ParagraphList::const_iterator pit = paragraphs().begin();
801 ParagraphList::const_iterator pend = paragraphs().end();
804 DocIterator inset_pos = text_inset_pos;
805 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
807 for (; pit != pend; ++pit, ++pidx) {
808 InsetList::const_iterator it = pit->insetList().begin();
809 InsetList::const_iterator end = pit->insetList().end();
810 inset_pos.pit() = pidx;
811 for (; it != end; ++it) {
812 inset_pos.pos() = it->pos;
813 it->inset->addPreview(inset_pos, loader);
819 ParagraphList const & InsetText::paragraphs() const
821 return text_.paragraphs();
825 ParagraphList & InsetText::paragraphs()
827 return text_.paragraphs();
831 bool InsetText::hasCProtectContent(bool fragile) const
833 fragile |= getLayout().isNeedProtect();
834 ParagraphList const & pars = paragraphs();
835 pit_type pend = pit_type(paragraphs().size());
836 for (pit_type pit = 0; pit != pend; ++pit) {
837 Paragraph const & par = pars[size_type(pit)];
838 if (par.needsCProtection(fragile))
845 bool InsetText::insetAllowed(InsetCode code) const
848 // Arguments and (plain) quotes are also allowed in PassThru insets
853 return !isPassThru();
858 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
860 ParIterator it2 = it;
862 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
863 if (producesOutput()) {
864 InsetLayout const & il = getLayout();
865 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
866 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
868 // LYXERR0("Entering " << name());
869 cnt.clearLastLayout();
870 // FIXME cnt.saveLastCounter()?
872 buffer().updateBuffer(it2, utype, deleted);
874 // LYXERR0("Exiting " << name());
875 cnt.restoreLastLayout();
876 // FIXME cnt.restoreLastCounter()?
878 // Record in this inset is embedded in a title layout
879 // This is needed to decide when \maketitle is output.
880 intitle_context_ = it.paragraph().layout().intitle;
881 // Also check embedding layouts
882 size_t const n = it.depth();
883 for (size_t i = 0; i < n; ++i) {
884 if (it[i].paragraph().layout().intitle) {
885 intitle_context_ = true;
890 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
891 // Note that we do not need to call:
892 // tclass.counters().clearLastLayout()
893 // since we are saving and restoring the existing counters, etc.
894 Counters savecnt = tclass.counters();
895 tclass.counters().reset();
896 // we need float information even in note insets (#9760)
897 tclass.counters().current_float(savecnt.current_float());
898 tclass.counters().isSubfloat(savecnt.isSubfloat());
899 buffer().updateBuffer(it2, utype, deleted);
900 tclass.counters() = move(savecnt);
905 void InsetText::toString(odocstream & os) const
907 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
911 void InsetText::forOutliner(docstring & os, size_t const maxlen,
912 bool const shorten) const
914 if (!getLayout().isInToc())
916 text().forOutliner(os, maxlen, shorten);
920 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
921 UpdateType utype, TocBackend & backend) const
923 DocIterator dit = cdit;
924 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
925 iterateForToc(dit, output_active, utype, backend);
929 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
930 UpdateType utype, TocBackend & backend) const
932 DocIterator dit = cdit;
933 // This also ensures that any document has a table of contents
934 shared_ptr<Toc> toc = backend.toc("tableofcontents");
936 BufferParams const & bufparams = buffer_->params();
937 int const min_toclevel = bufparams.documentClass().min_toclevel();
938 // we really should have done this before we got here, but it
939 // can't hurt too much to do it again
940 bool const doing_output = output_active && producesOutput();
942 // For each paragraph,
943 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
944 // paragraphs as needed.
945 // * Traverse its insets and let them add their toc items
946 // * Compute the main table of contents (this is hardcoded)
947 // * Add the list of changes
948 ParagraphList const & pars = paragraphs();
949 pit_type pend = paragraphs().size();
950 // Record pairs {start,end} of where a toc item was opened for a paragraph
951 // and where it must be closed
952 stack<pair<pit_type, pit_type>> addtotoc_stack;
954 for (pit_type pit = 0; pit != pend; ++pit) {
955 Paragraph const & par = pars[pit];
959 // Custom AddToToc in paragraph layouts (i.e. theorems)
960 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
962 openAddToTocForParagraph(pit, dit, output_active, backend);
963 addtotoc_stack.push({pit, end});
966 // If we find an InsetArgument that is supposed to provide the TOC caption,
967 // we'll save it for use later.
968 InsetArgument const * arginset = nullptr;
969 for (auto const & table : par.insetList()) {
970 dit.pos() = table.pos;
971 table.inset->addToToc(dit, doing_output, utype, backend);
972 if (InsetArgument const * x = table.inset->asInsetArgument())
973 if (x->isTocCaption())
977 // End custom AddToToc in paragraph layouts
978 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
979 // execute the closing function
980 closeAddToTocForParagraph(addtotoc_stack.top().first,
981 addtotoc_stack.top().second, backend);
982 addtotoc_stack.pop();
985 // now the toc entry for the paragraph in the main table of contents
986 int const toclevel = text().getTocLevel(pit);
987 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
988 // insert this into the table of contents
990 int const length = (doing_output && utype == OutputUpdate) ?
991 INT_MAX : TOC_ENTRY_LENGTH;
993 tocstring = par.labelString();
994 if (!tocstring.empty())
996 arginset->text().forOutliner(tocstring, length);
998 par.forOutliner(tocstring, length);
1000 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1001 tocstring, doing_output));
1004 // And now the list of changes.
1005 par.addChangesToToc(dit, buffer(), doing_output, backend);
1010 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1011 DocIterator const & dit,
1013 TocBackend & backend) const
1015 Paragraph const & par = paragraphs()[pit];
1016 TocBuilder & b = backend.builder(par.layout().tocType());
1017 docstring const & label = par.labelString();
1018 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1019 return text().lastInSequence(pit);
1023 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1024 TocBackend & backend) const
1026 Paragraph const & par = paragraphs()[start];
1027 TocBuilder & b = backend.builder(par.layout().tocType());
1028 if (par.layout().isTocCaption()) {
1030 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1031 b.argumentItem(str);
1037 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1039 if (buffer().isClean())
1040 return Inset::notifyCursorLeaves(old, cur);
1042 // find text inset in old cursor
1043 Cursor insetCur = old;
1044 int scriptSlice = insetCur.find(this);
1045 // we can try to continue here. returning true means
1046 // the cursor is "now" invalid. which it was.
1047 LASSERT(scriptSlice != -1, return true);
1048 insetCur.cutOff(scriptSlice);
1049 LASSERT(&insetCur.inset() == this, return true);
1051 // update the old paragraph's words
1052 insetCur.paragraph().updateWords();
1054 return Inset::notifyCursorLeaves(old, cur);
1058 bool InsetText::completionSupported(Cursor const & cur) const
1060 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1061 return text_.completionSupported(cur);
1065 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1067 return completionSupported(cur);
1071 bool InsetText::automaticInlineCompletion() const
1073 return lyxrc.completion_inline_text;
1077 bool InsetText::automaticPopupCompletion() const
1079 return lyxrc.completion_popup_text;
1083 bool InsetText::showCompletionCursor() const
1085 return lyxrc.completion_cursor_text;
1089 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1091 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1095 docstring InsetText::completionPrefix(Cursor const & cur) const
1097 if (!completionSupported(cur))
1099 return text_.completionPrefix(cur);
1103 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1106 if (!completionSupported(cur))
1109 return text_.insertCompletion(cur, s, finished);
1113 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1114 Dimension & dim) const
1116 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1117 tm.completionPosAndDim(cur, x, y, dim);
1121 string InsetText::contextMenu(BufferView const &, int, int) const
1123 string context_menu = contextMenuName();
1124 if (context_menu != InsetText::contextMenuName())
1125 context_menu += ";" + InsetText::contextMenuName();
1126 return context_menu;
1130 string InsetText::contextMenuName() const
1132 return "context-edit";
1136 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1138 OutputParams rp(&buffer().params().encoding());
1139 rp.for_tooltip = true;
1140 odocstringstream oss;
1143 ParagraphList::const_iterator beg = paragraphs().begin();
1144 ParagraphList::const_iterator end = paragraphs().end();
1145 ParagraphList::const_iterator it = beg;
1146 bool ref_printed = false;
1148 for (; it != end; ++it) {
1151 if ((*it).isRTL(buffer().params()))
1152 oss << "<div dir=\"rtl\">";
1153 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1154 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1157 docstring str = oss.str();
1159 str += from_ascii("\n\n") + _("[contains tracked changes]");
1160 support::truncateWithEllipsis(str, len);
1165 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1167 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1171 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1173 // Nested cprotect content needs \cprotect
1175 if (producesOutput() && hasCProtectContent(fragile))
1178 // Environments generally need cprotection in fragile context
1179 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1182 if (!getLayout().needsCProtect())
1185 // Environments and "no latex" types (e.g., knitr chunks)
1186 // need cprotection regardless the content
1187 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1190 // If the inset does not produce output (e.g. Note or Branch),
1191 // we can ignore the contained paragraphs
1192 if (!producesOutput())
1195 // Commands need cprotection if they contain specific chars
1196 int const nchars_escape = 9;
1197 static char_type const chars_escape[nchars_escape] = {
1198 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1200 ParagraphList const & pars = paragraphs();
1201 pit_type pend = pit_type(paragraphs().size());
1203 for (pit_type pit = 0; pit != pend; ++pit) {
1204 Paragraph const & par = pars[size_type(pit)];
1205 if (par.needsCProtection(fragile))
1207 docstring const par_str = par.asString();
1208 for (int k = 0; k < nchars_escape; k++) {
1209 if (contains(par_str, chars_escape[k]))