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"
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/RefChanger.h"
69 using namespace lyx::support;
74 using graphics::PreviewLoader;
77 /////////////////////////////////////////////////////////////////////
79 InsetText::InsetText(Buffer * buf, UsePlain type)
80 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
81 frame_color_(Color_insetframe),
82 text_(this, type == DefaultLayout)
87 InsetText::InsetText(InsetText const & in)
88 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
89 intitle_context_(false), frame_color_(in.frame_color_),
95 void InsetText::setBuffer(Buffer & buf)
97 ParagraphList::iterator end = paragraphs().end();
98 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
99 it->setInsetBuffers(buf);
100 Inset::setBuffer(buf);
104 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
106 text_.setMacrocontextPosition(pos);
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);
124 void InsetText::clear()
126 ParagraphList & pars = paragraphs();
127 LBUFERR(!pars.empty());
129 // This is a gross hack...
130 Layout const & old_layout = pars.begin()->layout();
133 pars.push_back(Paragraph());
134 pars.begin()->setInsetOwner(this);
135 pars.begin()->setLayout(old_layout);
139 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
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);
150 void InsetText::write(ostream & os) const
157 void InsetText::read(Lexer & lex)
161 // delete the initial paragraph
162 Paragraph oldpar = *paragraphs().begin();
163 paragraphs().clear();
165 lex.setContext("InsetText::read");
166 bool res = text_.read(lex, errorList, this);
169 lex.printError("Missing \\end_inset at this point. ");
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.
186 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
188 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
190 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
192 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
194 // Hand font through to contained lyxtext:
195 tm.font_.fontInfo() = mi.base.font;
196 mi.base.textwidth -= horiz_offset;
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;
205 tm.metrics(mi, dim, mi.base.textwidth);
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;
215 void InsetText::draw(PainterInfo & pi, int x, int y) const
217 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
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;
226 pi.pain.fillRectangle(xframe, yframe, w, h,
227 pi.backgroundColor(this));
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);
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.
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();
255 pi.pain.rectangle(xframe, yframe, w, h, c);
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);
266 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
268 pit_type const pit = front ? 0 : paragraphs().size() - 1;
269 pos_type pos = front ? 0 : paragraphs().back().size();
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();
280 cur.top().setPitPos(pit, pos);
285 Inset * InsetText::editXY(Cursor & cur, int x, int y)
287 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
291 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
293 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
295 // See bug #9042, for instance.
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);
307 switch (cmd.action()) {
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
315 // FIXME: Change only the pasted paragraphs
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());
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);
338 text_.dispatch(cur, cmd);
341 if (!cur.result().dispatched())
342 Inset::doDispatch(cur, cmd);
346 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
347 FuncStatus & status) const
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());
356 status.setEnabled(!main_inset);
360 case LFUN_ARGUMENT_INSERT: {
361 string const arg = cmd.getArg(0);
363 status.setEnabled(false);
366 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
367 return text_.getStatus(cur, cmd, status);
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);
382 status.setEnabled(false);
387 // Dispatch only to text_ if the cursor is inside
388 // the text_. It is not for context menus (bug 5797).
390 if (cur.text() == &text_)
391 ret = text_.getStatus(cur, cmd, status);
394 ret = Inset::getStatus(cur, cmd, status);
400 void InsetText::fixParagraphsFont()
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();
407 if (par->isPassThru())
408 par->resetFonts(font);
409 if (!par->allowParagraphCustomization())
410 par->params().clear();
416 // bool InsetText::isChanged() const
418 // ParagraphList::const_iterator pit = paragraphs().begin();
419 // ParagraphList::const_iterator end = paragraphs().end();
420 // for (; pit != end; ++pit) {
421 // if (pit->isChanged())
428 void InsetText::setChange(Change const & change)
430 ParagraphList::iterator pit = paragraphs().begin();
431 ParagraphList::iterator end = paragraphs().end();
432 for (; pit != end; ++pit) {
433 pit->setChange(change);
438 void InsetText::acceptChanges()
440 text_.acceptChanges();
444 void InsetText::rejectChanges()
446 text_.rejectChanges();
450 void InsetText::validate(LaTeXFeatures & features) const
452 features.useInsetLayout(getLayout());
453 for (Paragraph const & p : paragraphs())
454 p.validate(features);
458 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
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())
467 bool needendgroup = false;
468 if (!il.latexname().empty()) {
469 if (il.latextype() == InsetLayout::COMMAND) {
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";
480 } else if (runparams.moving_arg)
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());
488 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
493 if (runparams.lastid != -1)
494 os.texrow().start(runparams.lastid,
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());
504 if (!il.latexargs().empty())
505 getArgs(os, runparams);
506 if (!il.latexparam().empty())
507 os << from_utf8(il.latexparam());
510 if (!il.leftdelim().empty())
511 os << il.leftdelim();
513 OutputParams rp = runparams;
516 if (il.isNeedProtect())
517 rp.moving_arg = true;
518 if (il.isNeedMBoxProtect())
520 if (!il.passThruChars().empty())
521 rp.pass_thru_chars += il.passThruChars();
522 if (!il.newlineCmd().empty())
523 rp.newlinecmd = il.newlineCmd();
525 rp.par_end = paragraphs().size();
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;
536 if (!il.rightdelim().empty())
537 os << il.rightdelim();
539 if (!il.latexname().empty()) {
540 if (il.latextype() == InsetLayout::COMMAND) {
542 if (!il.postcommandargs().empty())
543 getArgs(os, runparams, true);
546 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
547 // A comment environment doesn't need a % before \n\end
548 if (il.isDisplay() || runparams.inComment)
552 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
554 os.protectSpace(true);
557 if (il.forceOwnlines())
562 int InsetText::plaintext(odocstringstream & os,
563 OutputParams const & runparams, size_t max_length) const
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;
570 for (; it != end; ++it) {
573 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
576 odocstringstream oss;
577 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
578 docstring const str = oss.str();
580 // FIXME: len is not computed fully correctly; in principle,
581 // we have to count the characters after the last '\n'
583 if (os.str().size() >= max_length)
592 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
594 docbook(xs, rp, WriteEverything);
598 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
600 // we will always want to output all our paragraphs when we are
602 OutputParams runparams = rp;
603 runparams.par_begin = 0;
604 runparams.par_end = text().paragraphs().size();
607 xs.startDivision(false);
608 docbookParagraphs(text_, buffer(), xs, runparams);
613 InsetLayout const & il = getLayout();
614 if (opts & WriteOuterTag && !il.docbooktag().empty() && il.docbooktag() != "NONE") {
615 docstring attrs = docstring();
616 if (!il.docbookattr().empty())
617 attrs += from_ascii(il.docbookattr());
618 if (il.docbooktag() == "link")
619 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
620 xs << xml::StartTag(il.docbooktag(), attrs);
623 // No need for labels that are generated from counters.
625 // With respect to XHTML, paragraphs are still allowed here.
626 if (!allowMultiPar())
627 runparams.docbook_make_pars = false;
629 runparams.pass_thru = true;
631 xs.startDivision(false);
632 docbookParagraphs(text_, buffer(), xs, runparams);
635 if (opts & WriteOuterTag)
636 xs << xml::EndTag(il.docbooktag());
640 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
642 return insetAsXHTML(xs, runparams, WriteEverything);
647 // There are cases where we may need to close open fonts and such
648 // and then re-open them when we are done. This would be the case, e.g.,
649 // if we were otherwise about to write:
650 // <em>word <div class='foot'>footnote text.</div> emph</em>
651 // The problem isn't so much that the footnote text will get emphasized:
652 // we can handle that with CSS. The problem is that this is invalid XHTML.
653 // One solution would be to make the footnote <span>, but the problem is
654 // completely general, and so we'd have to make absolutely everything into
655 // span. What I think will work is to check if we're about to write "div" and,
656 // if so, try to close fonts, etc.
657 // There are probably limits to how well we can do here, though, and we will
658 // have to rely upon users not putting footnotes inside noun-type insets.
659 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
660 XHTMLOptions opts) const
662 // we will always want to output all our paragraphs when we are
664 OutputParams runparams = rp;
665 runparams.par_begin = 0;
666 runparams.par_end = text().paragraphs().size();
669 xs.startDivision(false);
670 xhtmlParagraphs(text_, buffer(), xs, runparams);
675 InsetLayout const & il = getLayout();
676 if (opts & WriteOuterTag)
677 xs << xml::StartTag(il.htmltag(), il.htmlattr());
679 if ((opts & WriteLabel) && !il.counter().empty()) {
680 BufferParams const & bp = buffer().masterBuffer()->params();
681 Counters & cntrs = bp.documentClass().counters();
682 cntrs.step(il.counter(), OutputUpdate);
683 // FIXME: translate to paragraph language
684 if (!il.htmllabel().empty()) {
685 docstring const lbl =
686 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
687 // FIXME is this check necessary?
689 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
691 xs << xml::EndTag(il.htmllabeltag());
696 if (opts & WriteInnerTag)
697 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
699 // we will eventually lose information about the containing inset
700 if (!allowMultiPar() || opts == JustText)
701 runparams.html_make_pars = false;
703 runparams.pass_thru = true;
705 xs.startDivision(false);
706 xhtmlParagraphs(text_, buffer(), xs, runparams);
709 if (opts & WriteInnerTag)
710 xs << xml::EndTag(il.htmlinnertag());
712 if (opts & WriteOuterTag)
713 xs << xml::EndTag(il.htmltag());
719 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
720 bool const post) const
722 OutputParams runparams = runparams_in;
723 runparams.local_font =
724 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
726 runparams.pass_thru = true;
728 latexArgInsetsForParent(paragraphs(), os, runparams,
729 getLayout().postcommandargs(), "post:");
731 latexArgInsetsForParent(paragraphs(), os, runparams,
732 getLayout().latexargs());
736 void InsetText::cursorPos(BufferView const & bv,
737 CursorSlice const & sl, bool boundary, int & x, int & y) const
739 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
740 y = bv.textMetrics(&text_).cursorY(sl, boundary);
744 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
747 Paragraph & first = paragraphs().front();
748 for (unsigned int i = 0; i < data.length(); ++i)
749 first.insertChar(i, data[i], font, trackChanges);
753 void InsetText::setDrawFrame(bool flag)
759 ColorCode InsetText::frameColor() const
765 void InsetText::setFrameColor(ColorCode col)
771 void InsetText::appendParagraphs(ParagraphList & plist)
773 // There is little we can do here to keep track of changes.
774 // As of 2006/10/20, appendParagraphs is used exclusively by
775 // LyXTabular::setMultiColumn. In this context, the paragraph break
776 // is lost irreversibly and the appended text doesn't really change
778 ParagraphList & pl = paragraphs();
780 ParagraphList::iterator pit = plist.begin();
781 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
783 mergeParagraph(buffer().params(), pl,
784 distance(pl.begin(), ins) - 1);
786 ParagraphList::iterator const pend = plist.end();
787 for (; pit != pend; ++pit)
792 void InsetText::addPreview(DocIterator const & text_inset_pos,
793 PreviewLoader & loader) const
795 ParagraphList::const_iterator pit = paragraphs().begin();
796 ParagraphList::const_iterator pend = paragraphs().end();
799 DocIterator inset_pos = text_inset_pos;
800 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
802 for (; pit != pend; ++pit, ++pidx) {
803 InsetList::const_iterator it = pit->insetList().begin();
804 InsetList::const_iterator end = pit->insetList().end();
805 inset_pos.pit() = pidx;
806 for (; it != end; ++it) {
807 inset_pos.pos() = it->pos;
808 it->inset->addPreview(inset_pos, loader);
814 ParagraphList const & InsetText::paragraphs() const
816 return text_.paragraphs();
820 ParagraphList & InsetText::paragraphs()
822 return text_.paragraphs();
826 bool InsetText::hasCProtectContent(bool fragile) const
828 fragile |= getLayout().isNeedProtect();
829 ParagraphList const & pars = paragraphs();
830 pit_type pend = pit_type(paragraphs().size());
831 for (pit_type pit = 0; pit != pend; ++pit) {
832 Paragraph const & par = pars[size_type(pit)];
833 if (par.needsCProtection(fragile))
840 bool InsetText::insetAllowed(InsetCode code) const
843 // Arguments and (plain) quotes are also allowed in PassThru insets
848 return !isPassThru();
853 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
855 ParIterator it2 = it;
857 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
858 if (producesOutput()) {
859 InsetLayout const & il = getLayout();
860 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
861 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
863 // LYXERR0("Entering " << name());
864 cnt.clearLastLayout();
865 // FIXME cnt.saveLastCounter()?
867 buffer().updateBuffer(it2, utype, deleted);
869 // LYXERR0("Exiting " << name());
870 cnt.restoreLastLayout();
871 // FIXME cnt.restoreLastCounter()?
873 // Record in this inset is embedded in a title layout
874 // This is needed to decide when \maketitle is output.
875 intitle_context_ = it.paragraph().layout().intitle;
876 // Also check embedding layouts
877 size_t const n = it.depth();
878 for (size_t i = 0; i < n; ++i) {
879 if (it[i].paragraph().layout().intitle) {
880 intitle_context_ = true;
885 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
886 // Note that we do not need to call:
887 // tclass.counters().clearLastLayout()
888 // since we are saving and restoring the existing counters, etc.
889 Counters savecnt = tclass.counters();
890 tclass.counters().reset();
891 // we need float information even in note insets (#9760)
892 tclass.counters().current_float(savecnt.current_float());
893 tclass.counters().isSubfloat(savecnt.isSubfloat());
894 buffer().updateBuffer(it2, utype, deleted);
895 tclass.counters() = move(savecnt);
900 void InsetText::toString(odocstream & os) const
902 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
906 void InsetText::forOutliner(docstring & os, size_t const maxlen,
907 bool const shorten) const
909 if (!getLayout().isInToc())
911 text().forOutliner(os, maxlen, shorten);
915 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
916 UpdateType utype, TocBackend & backend) const
918 DocIterator dit = cdit;
919 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
920 iterateForToc(dit, output_active, utype, backend);
924 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
925 UpdateType utype, TocBackend & backend) const
927 DocIterator dit = cdit;
928 // This also ensures that any document has a table of contents
929 shared_ptr<Toc> toc = backend.toc("tableofcontents");
931 BufferParams const & bufparams = buffer_->params();
932 int const min_toclevel = bufparams.documentClass().min_toclevel();
933 // we really should have done this before we got here, but it
934 // can't hurt too much to do it again
935 bool const doing_output = output_active && producesOutput();
937 // For each paragraph,
938 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
939 // paragraphs as needed.
940 // * Traverse its insets and let them add their toc items
941 // * Compute the main table of contents (this is hardcoded)
942 // * Add the list of changes
943 ParagraphList const & pars = paragraphs();
944 pit_type pend = paragraphs().size();
945 // Record pairs {start,end} of where a toc item was opened for a paragraph
946 // and where it must be closed
947 stack<pair<pit_type, pit_type>> addtotoc_stack;
949 for (pit_type pit = 0; pit != pend; ++pit) {
950 Paragraph const & par = pars[pit];
954 // Custom AddToToc in paragraph layouts (i.e. theorems)
955 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
957 openAddToTocForParagraph(pit, dit, output_active, backend);
958 addtotoc_stack.push({pit, end});
961 // If we find an InsetArgument that is supposed to provide the TOC caption,
962 // we'll save it for use later.
963 InsetArgument const * arginset = nullptr;
964 for (auto const & table : par.insetList()) {
965 dit.pos() = table.pos;
966 table.inset->addToToc(dit, doing_output, utype, backend);
967 if (InsetArgument const * x = table.inset->asInsetArgument())
968 if (x->isTocCaption())
972 // End custom AddToToc in paragraph layouts
973 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
974 // execute the closing function
975 closeAddToTocForParagraph(addtotoc_stack.top().first,
976 addtotoc_stack.top().second, backend);
977 addtotoc_stack.pop();
980 // now the toc entry for the paragraph in the main table of contents
981 int const toclevel = text().getTocLevel(pit);
982 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
983 // insert this into the table of contents
985 int const length = (doing_output && utype == OutputUpdate) ?
986 INT_MAX : TOC_ENTRY_LENGTH;
988 tocstring = par.labelString();
989 if (!tocstring.empty())
991 arginset->text().forOutliner(tocstring, length);
993 par.forOutliner(tocstring, length);
995 toc->push_back(TocItem(dit, toclevel - min_toclevel,
996 tocstring, doing_output));
999 // And now the list of changes.
1000 par.addChangesToToc(dit, buffer(), doing_output, backend);
1005 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1006 DocIterator const & dit,
1008 TocBackend & backend) const
1010 Paragraph const & par = paragraphs()[pit];
1011 TocBuilder & b = backend.builder(par.layout().tocType());
1012 docstring const label = par.labelString();
1013 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1014 return text().lastInSequence(pit);
1018 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1019 TocBackend & backend) const
1021 Paragraph const & par = paragraphs()[start];
1022 TocBuilder & b = backend.builder(par.layout().tocType());
1023 if (par.layout().isTocCaption()) {
1025 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1026 b.argumentItem(str);
1032 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1034 if (buffer().isClean())
1035 return Inset::notifyCursorLeaves(old, cur);
1037 // find text inset in old cursor
1038 Cursor insetCur = old;
1039 int scriptSlice = insetCur.find(this);
1040 // we can try to continue here. returning true means
1041 // the cursor is "now" invalid. which it was.
1042 LASSERT(scriptSlice != -1, return true);
1043 insetCur.cutOff(scriptSlice);
1044 LASSERT(&insetCur.inset() == this, return true);
1046 // update the old paragraph's words
1047 insetCur.paragraph().updateWords();
1049 return Inset::notifyCursorLeaves(old, cur);
1053 bool InsetText::completionSupported(Cursor const & cur) const
1055 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1056 return text_.completionSupported(cur);
1060 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1062 return completionSupported(cur);
1066 bool InsetText::automaticInlineCompletion() const
1068 return lyxrc.completion_inline_text;
1072 bool InsetText::automaticPopupCompletion() const
1074 return lyxrc.completion_popup_text;
1078 bool InsetText::showCompletionCursor() const
1080 return lyxrc.completion_cursor_text;
1084 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1086 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1090 docstring InsetText::completionPrefix(Cursor const & cur) const
1092 if (!completionSupported(cur))
1094 return text_.completionPrefix(cur);
1098 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1101 if (!completionSupported(cur))
1104 return text_.insertCompletion(cur, s, finished);
1108 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1109 Dimension & dim) const
1111 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1112 tm.completionPosAndDim(cur, x, y, dim);
1116 string InsetText::contextMenu(BufferView const &, int, int) const
1118 string context_menu = contextMenuName();
1119 if (context_menu != InsetText::contextMenuName())
1120 context_menu += ";" + InsetText::contextMenuName();
1121 return context_menu;
1125 string InsetText::contextMenuName() const
1127 return "context-edit";
1131 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1133 OutputParams rp(&buffer().params().encoding());
1134 rp.for_tooltip = true;
1135 odocstringstream oss;
1138 ParagraphList::const_iterator beg = paragraphs().begin();
1139 ParagraphList::const_iterator end = paragraphs().end();
1140 ParagraphList::const_iterator it = beg;
1141 bool ref_printed = false;
1143 for (; it != end; ++it) {
1146 if ((*it).isRTL(buffer().params()))
1147 oss << "<div dir=\"rtl\">";
1148 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1149 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1152 docstring str = oss.str();
1154 str += from_ascii("\n\n") + _("[contains tracked changes]");
1155 support::truncateWithEllipsis(str, len);
1160 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1162 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1166 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1168 // Nested cprotect content needs \cprotect
1170 if (producesOutput() && hasCProtectContent(fragile))
1173 // Environments generally need cprotection in fragile context
1174 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1177 if (!getLayout().needsCProtect())
1180 // Environments and "no latex" types (e.g., knitr chunks)
1181 // need cprotection regardless the content
1182 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1185 // If the inset does not produce output (e.g. Note or Branch),
1186 // we can ignore the contained paragraphs
1187 if (!producesOutput())
1190 // Commands need cprotection if they contain specific chars
1191 int const nchars_escape = 9;
1192 static char_type const chars_escape[nchars_escape] = {
1193 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1195 ParagraphList const & pars = paragraphs();
1196 pit_type pend = pit_type(paragraphs().size());
1198 for (pit_type pit = 0; pit != pend; ++pit) {
1199 Paragraph const & par = pars[size_type(pit)];
1200 if (par.needsCProtection(fragile))
1202 docstring const par_str = par.asString();
1203 for (int k = 0; k < nchars_escape; k++) {
1204 if (contains(par_str, chars_escape[k]))