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_xhtml.h"
42 #include "OutputParams.h"
43 #include "output_plaintext.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
50 #include "texstream.h"
51 #include "TextClass.h"
53 #include "TextMetrics.h"
54 #include "TocBackend.h"
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
59 #include "support/bind.h"
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/RefChanger.h"
71 using namespace lyx::support;
76 using graphics::PreviewLoader;
79 /////////////////////////////////////////////////////////////////////
81 InsetText::InsetText(Buffer * buf, UsePlain type)
82 : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
83 text_(this, type == DefaultLayout)
88 InsetText::InsetText(InsetText const & in)
89 : Inset(in), drawFrame_(in.drawFrame_), 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 += 2 * TEXT_TO_INSET_OFFSET;
144 dim.des += TEXT_TO_INSET_OFFSET;
145 dim.asc += TEXT_TO_INSET_OFFSET;
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 // Hand font through to contained lyxtext:
193 tm.font_.fontInfo() = mi.base.font;
194 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
196 // This can happen when a layout has a left and right margin,
197 // and the view is made very narrow. We can't do better than
198 // to draw it partly out of view (bug 5890).
199 if (mi.base.textwidth < 1)
200 mi.base.textwidth = 1;
203 tm.metrics(mi, dim, mi.base.textwidth);
206 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
207 dim.asc += TEXT_TO_INSET_OFFSET;
208 dim.des += TEXT_TO_INSET_OFFSET;
209 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
213 void InsetText::draw(PainterInfo & pi, int x, int y) const
215 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
217 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
218 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
219 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
220 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
221 bool change_drawn = false;
223 pi.pain.fillRectangle(xframe, yframe, w, h,
224 pi.backgroundColor(this));
227 Changer dummy = make_change(pi.background_color,
228 pi.backgroundColor(this, false));
229 // The change tracking cue must not be inherited
230 Changer dummy2 = make_change(pi.change_, Change());
231 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
235 // Change color of the frame in tracked changes, like for tabulars.
236 // Only do so if the color is not custom. But do so even if RowPainter
237 // handles the strike-through already.
239 if (pi.change_.changed()
240 // Originally, these are the colors with role Text, from role() in
241 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
242 // types, and also maybe it need not match in the future.
243 && (frameColor() == Color_foreground
244 || frameColor() == Color_cursor
245 || frameColor() == Color_preview
246 || frameColor() == Color_tabularline
247 || frameColor() == Color_previewframe)) {
248 c = pi.change_.color();
252 pi.pain.rectangle(xframe, yframe, w, h, c);
255 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
256 // Do not draw the change tracking cue if already done by RowPainter and
257 // do not draw the cue for INSERTED if the information is already in the
258 // color of the frame
259 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
263 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
265 pit_type const pit = front ? 0 : paragraphs().size() - 1;
266 pos_type pos = front ? 0 : paragraphs().back().size();
268 // if visual information is not to be ignored, move to extreme right/left
269 if (entry_from != ENTRY_DIRECTION_IGNORE) {
270 Cursor temp_cur = cur;
271 temp_cur.pit() = pit;
272 temp_cur.pos() = pos;
273 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
274 pos = temp_cur.pos();
277 cur.top().setPitPos(pit, pos);
282 Inset * InsetText::editXY(Cursor & cur, int x, int y)
284 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
288 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
290 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
292 // See bug #9042, for instance.
294 // Force any new text to latex_language FIXME: This
295 // should only be necessary in constructor, but new
296 // paragraphs that are created by pressing enter at
297 // the start of an existing paragraph get the buffer
298 // language and not latex_language, so we take this
299 // brute force approach.
300 cur.current_font.setLanguage(latex_language);
301 cur.real_current_font.setLanguage(latex_language);
304 switch (cmd.action()) {
306 case LFUN_CLIPBOARD_PASTE:
307 case LFUN_SELECTION_PASTE:
308 case LFUN_PRIMARY_SELECTION_PASTE:
309 text_.dispatch(cur, cmd);
310 // If we we can only store plain text, we must reset all
312 // FIXME: Change only the pasted paragraphs
316 case LFUN_INSET_DISSOLVE: {
317 bool const main_inset = text_.isMainText();
318 bool const target_inset = cmd.argument().empty()
319 || cmd.getArg(0) == insetName(lyxCode());
321 if (!main_inset && target_inset) {
322 // Text::dissolveInset assumes that the cursor
323 // is inside the Inset.
324 if (&cur.inset() != this)
325 cur.pushBackward(*this);
326 cur.beginUndoGroup();
327 text_.dispatch(cur, cmd);
335 text_.dispatch(cur, cmd);
338 if (!cur.result().dispatched())
339 Inset::doDispatch(cur, cmd);
343 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
344 FuncStatus & status) const
346 switch (cmd.action()) {
347 case LFUN_INSET_DISSOLVE: {
348 bool const main_inset = text_.isMainText();
349 bool const target_inset = cmd.argument().empty()
350 || cmd.getArg(0) == insetName(lyxCode());
353 status.setEnabled(!main_inset);
357 case LFUN_ARGUMENT_INSERT: {
358 string const arg = cmd.getArg(0);
360 status.setEnabled(false);
363 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
364 return text_.getStatus(cur, cmd, status);
366 Layout::LaTeXArgMap args = getLayout().args();
367 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
368 if (lait != args.end()) {
369 status.setEnabled(true);
370 for (Paragraph const & par : paragraphs())
371 for (auto const & table : par.insetList())
372 if (InsetArgument const * ins = table.inset->asInsetArgument())
373 if (ins->name() == arg) {
374 // we have this already
375 status.setEnabled(false);
379 status.setEnabled(false);
384 // Dispatch only to text_ if the cursor is inside
385 // the text_. It is not for context menus (bug 5797).
387 if (cur.text() == &text_)
388 ret = text_.getStatus(cur, cmd, status);
391 ret = Inset::getStatus(cur, cmd, status);
397 void InsetText::fixParagraphsFont()
399 Font font(inherit_font, buffer().params().language);
400 font.setLanguage(latex_language);
401 ParagraphList::iterator par = paragraphs().begin();
402 ParagraphList::iterator const end = paragraphs().end();
404 if (par->isPassThru())
405 par->resetFonts(font);
406 if (!par->allowParagraphCustomization())
407 par->params().clear();
413 void InsetText::setChange(Change const & change)
415 ParagraphList::iterator pit = paragraphs().begin();
416 ParagraphList::iterator end = paragraphs().end();
417 for (; pit != end; ++pit) {
418 pit->setChange(change);
423 void InsetText::acceptChanges()
425 text_.acceptChanges();
429 void InsetText::rejectChanges()
431 text_.rejectChanges();
435 void InsetText::validate(LaTeXFeatures & features) const
437 features.useInsetLayout(getLayout());
438 for (Paragraph const & p : paragraphs())
439 p.validate(features);
443 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
445 // This implements the standard way of handling the LaTeX
446 // output of a text inset, either a command or an
447 // environment. Standard collapsible insets should not
448 // redefine this, non-standard ones may call this.
449 InsetLayout const & il = getLayout();
450 if (il.forceOwnlines())
452 bool needendgroup = false;
453 if (!il.latexname().empty()) {
454 if (il.latextype() == InsetLayout::COMMAND) {
456 // FIXME \protect should only be used for fragile
457 // commands, but we do not provide this information yet.
458 if (hasCProtectContent(runparams.moving_arg)) {
459 if (contains(runparams.active_chars, '^')) {
460 // cprotect relies on ^ being on catcode 7
461 os << "\\begingroup\\catcode`\\^=7";
465 } else if (runparams.moving_arg)
467 os << '\\' << from_utf8(il.latexname());
468 if (!il.latexargs().empty())
469 getArgs(os, runparams);
470 if (!il.latexparam().empty())
471 os << from_utf8(il.latexparam());
473 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
478 if (runparams.lastid != -1)
479 os.texrow().start(runparams.lastid,
481 os << "\\begin{" << from_utf8(il.latexname()) << "}";
482 if (!il.latexargs().empty())
483 getArgs(os, runparams);
484 if (!il.latexparam().empty())
485 os << from_utf8(il.latexparam());
489 if (!il.latexargs().empty())
490 getArgs(os, runparams);
491 if (!il.latexparam().empty())
492 os << from_utf8(il.latexparam());
495 if (!il.leftdelim().empty())
496 os << il.leftdelim();
498 OutputParams rp = runparams;
501 if (il.isNeedProtect())
502 rp.moving_arg = true;
503 if (il.isNeedMBoxProtect())
505 if (!il.passThruChars().empty())
506 rp.pass_thru_chars += il.passThruChars();
507 if (!il.newlineCmd().empty())
508 rp.newlinecmd = il.newlineCmd();
510 rp.par_end = paragraphs().size();
512 // Output the contents of the inset
513 latexParagraphs(buffer(), text_, os, rp);
514 runparams.encoding = rp.encoding;
515 // Pass the post_macros upstream
516 runparams.post_macro = rp.post_macro;
518 if (!il.rightdelim().empty())
519 os << il.rightdelim();
521 if (!il.latexname().empty()) {
522 if (il.latextype() == InsetLayout::COMMAND) {
524 if (!il.postcommandargs().empty())
525 getArgs(os, runparams, true);
528 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
529 // A comment environment doesn't need a % before \n\end
530 if (il.isDisplay() || runparams.inComment)
534 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
536 os.protectSpace(true);
539 if (il.forceOwnlines())
544 int InsetText::plaintext(odocstringstream & os,
545 OutputParams const & runparams, size_t max_length) const
547 ParagraphList::const_iterator beg = paragraphs().begin();
548 ParagraphList::const_iterator end = paragraphs().end();
549 ParagraphList::const_iterator it = beg;
550 bool ref_printed = false;
552 for (; it != end; ++it) {
555 if (runparams.linelen > 0)
558 odocstringstream oss;
559 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
560 docstring const str = oss.str();
562 // FIXME: len is not computed fully correctly; in principle,
563 // we have to count the characters after the last '\n'
565 if (os.str().size() >= max_length)
573 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
575 ParagraphList::const_iterator const beg = paragraphs().begin();
578 sgml::openTag(os, getLayout().latexname(),
579 beg->getID(buffer(), runparams) + getLayout().latexparam());
581 docbookParagraphs(text_, buffer(), os, runparams);
584 sgml::closeTag(os, getLayout().latexname());
590 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
592 return insetAsXHTML(xs, runparams, WriteEverything);
597 // There are cases where we may need to close open fonts and such
598 // and then re-open them when we are done. This would be the case, e.g.,
599 // if we were otherwise about to write:
600 // <em>word <div class='foot'>footnote text.</div> emph</em>
601 // The problem isn't so much that the footnote text will get emphasized:
602 // we can handle that with CSS. The problem is that this is invalid XHTML.
603 // One solution would be to make the footnote <span>, but the problem is
604 // completely general, and so we'd have to make absolutely everything into
605 // span. What I think will work is to check if we're about to write "div" and,
606 // if so, try to close fonts, etc.
607 // There are probably limits to how well we can do here, though, and we will
608 // have to rely upon users not putting footnotes inside noun-type insets.
609 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
610 XHTMLOptions opts) const
612 // we will always want to output all our paragraphs when we are
614 OutputParams runparams = rp;
615 runparams.par_begin = 0;
616 runparams.par_end = text().paragraphs().size();
619 xs.startDivision(false);
620 xhtmlParagraphs(text_, buffer(), xs, runparams);
625 InsetLayout const & il = getLayout();
626 if (opts & WriteOuterTag)
627 xs << html::StartTag(il.htmltag(), il.htmlattr());
629 if ((opts & WriteLabel) && !il.counter().empty()) {
630 BufferParams const & bp = buffer().masterBuffer()->params();
631 Counters & cntrs = bp.documentClass().counters();
632 cntrs.step(il.counter(), OutputUpdate);
633 // FIXME: translate to paragraph language
634 if (!il.htmllabel().empty()) {
635 docstring const lbl =
636 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
637 // FIXME is this check necessary?
639 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
641 xs << html::EndTag(il.htmllabeltag());
646 if (opts & WriteInnerTag)
647 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
649 // we will eventually lose information about the containing inset
650 if (!allowMultiPar() || opts == JustText)
651 runparams.html_make_pars = false;
653 runparams.pass_thru = true;
655 xs.startDivision(false);
656 xhtmlParagraphs(text_, buffer(), xs, runparams);
659 if (opts & WriteInnerTag)
660 xs << html::EndTag(il.htmlinnertag());
662 if (opts & WriteOuterTag)
663 xs << html::EndTag(il.htmltag());
669 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
670 bool const post) const
672 OutputParams runparams = runparams_in;
673 runparams.local_font =
674 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
676 runparams.pass_thru = true;
678 latexArgInsetsForParent(paragraphs(), os, runparams,
679 getLayout().postcommandargs(), "post:");
681 latexArgInsetsForParent(paragraphs(), os, runparams,
682 getLayout().latexargs());
686 void InsetText::cursorPos(BufferView const & bv,
687 CursorSlice const & sl, bool boundary, int & x, int & y) const
689 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
690 y = bv.textMetrics(&text_).cursorY(sl, boundary);
694 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
697 Paragraph & first = paragraphs().front();
698 for (unsigned int i = 0; i < data.length(); ++i)
699 first.insertChar(i, data[i], font, trackChanges);
703 void InsetText::setDrawFrame(bool flag)
709 ColorCode InsetText::frameColor() const
715 void InsetText::setFrameColor(ColorCode col)
721 void InsetText::appendParagraphs(ParagraphList & plist)
723 // There is little we can do here to keep track of changes.
724 // As of 2006/10/20, appendParagraphs is used exclusively by
725 // LyXTabular::setMultiColumn. In this context, the paragraph break
726 // is lost irreversibly and the appended text doesn't really change
728 ParagraphList & pl = paragraphs();
730 ParagraphList::iterator pit = plist.begin();
731 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
733 mergeParagraph(buffer().params(), pl,
734 distance(pl.begin(), ins) - 1);
736 for_each(pit, plist.end(),
737 bind(&ParagraphList::push_back, ref(pl), _1));
741 void InsetText::addPreview(DocIterator const & text_inset_pos,
742 PreviewLoader & loader) const
744 ParagraphList::const_iterator pit = paragraphs().begin();
745 ParagraphList::const_iterator pend = paragraphs().end();
748 DocIterator inset_pos = text_inset_pos;
749 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
751 for (; pit != pend; ++pit, ++pidx) {
752 InsetList::const_iterator it = pit->insetList().begin();
753 InsetList::const_iterator end = pit->insetList().end();
754 inset_pos.pit() = pidx;
755 for (; it != end; ++it) {
756 inset_pos.pos() = it->pos;
757 it->inset->addPreview(inset_pos, loader);
763 ParagraphList const & InsetText::paragraphs() const
765 return text_.paragraphs();
769 ParagraphList & InsetText::paragraphs()
771 return text_.paragraphs();
775 bool InsetText::hasCProtectContent(bool fragile) const
777 fragile |= getLayout().isNeedProtect();
778 ParagraphList const & pars = paragraphs();
779 pit_type pend = pit_type(paragraphs().size());
780 for (pit_type pit = 0; pit != pend; ++pit) {
781 Paragraph const & par = pars[size_type(pit)];
782 if (par.needsCProtection(fragile))
789 bool InsetText::insetAllowed(InsetCode code) const
792 // Arguments and (plain) quotes are also allowed in PassThru insets
797 return !isPassThru();
802 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
804 ParIterator it2 = it;
806 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
807 if (producesOutput()) {
808 InsetLayout const & il = getLayout();
809 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
810 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
812 // LYXERR0("Entering " << name());
813 cnt.clearLastLayout();
814 // FIXME cnt.saveLastCounter()?
816 buffer().updateBuffer(it2, utype);
818 // LYXERR0("Exiting " << name());
819 cnt.restoreLastLayout();
820 // FIXME cnt.restoreLastCounter()?
823 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
824 // Note that we do not need to call:
825 // tclass.counters().clearLastLayout()
826 // since we are saving and restoring the existing counters, etc.
827 Counters savecnt = tclass.counters();
828 tclass.counters().reset();
829 // we need float information even in note insets (#9760)
830 tclass.counters().current_float(savecnt.current_float());
831 tclass.counters().isSubfloat(savecnt.isSubfloat());
832 buffer().updateBuffer(it2, utype);
833 tclass.counters() = move(savecnt);
838 void InsetText::toString(odocstream & os) const
840 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
844 void InsetText::forOutliner(docstring & os, size_t const maxlen,
845 bool const shorten) const
847 if (!getLayout().isInToc())
849 text().forOutliner(os, maxlen, shorten);
853 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
854 UpdateType utype, TocBackend & backend) const
856 DocIterator dit = cdit;
857 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
858 iterateForToc(dit, output_active, utype, backend);
862 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
863 UpdateType utype, TocBackend & backend) const
865 DocIterator dit = cdit;
866 // This also ensures that any document has a table of contents
867 shared_ptr<Toc> toc = backend.toc("tableofcontents");
869 BufferParams const & bufparams = buffer_->params();
870 int const min_toclevel = bufparams.documentClass().min_toclevel();
871 // we really should have done this before we got here, but it
872 // can't hurt too much to do it again
873 bool const doing_output = output_active && producesOutput();
875 // For each paragraph,
876 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
877 // paragraphs as needed.
878 // * Traverse its insets and let them add their toc items
879 // * Compute the main table of contents (this is hardcoded)
880 // * Add the list of changes
881 ParagraphList const & pars = paragraphs();
882 pit_type pend = paragraphs().size();
883 // Record pairs {start,end} of where a toc item was opened for a paragraph
884 // and where it must be closed
885 stack<pair<pit_type, pit_type>> addtotoc_stack;
887 for (pit_type pit = 0; pit != pend; ++pit) {
888 Paragraph const & par = pars[pit];
892 // Custom AddToToc in paragraph layouts (i.e. theorems)
893 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
895 openAddToTocForParagraph(pit, dit, output_active, backend);
896 addtotoc_stack.push({pit, end});
899 // If we find an InsetArgument that is supposed to provide the TOC caption,
900 // we'll save it for use later.
901 InsetArgument const * arginset = nullptr;
902 for (auto const & table : par.insetList()) {
903 dit.pos() = table.pos;
904 table.inset->addToToc(dit, doing_output, utype, backend);
905 if (InsetArgument const * x = table.inset->asInsetArgument())
906 if (x->isTocCaption())
910 // End custom AddToToc in paragraph layouts
911 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
912 // execute the closing function
913 closeAddToTocForParagraph(addtotoc_stack.top().first,
914 addtotoc_stack.top().second, backend);
915 addtotoc_stack.pop();
918 // now the toc entry for the paragraph in the main table of contents
919 int const toclevel = text().getTocLevel(pit);
920 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
921 // insert this into the table of contents
923 int const length = (doing_output && utype == OutputUpdate) ?
924 INT_MAX : TOC_ENTRY_LENGTH;
926 tocstring = par.labelString();
927 if (!tocstring.empty())
929 arginset->text().forOutliner(tocstring, length);
931 par.forOutliner(tocstring, length);
933 toc->push_back(TocItem(dit, toclevel - min_toclevel,
934 tocstring, doing_output));
937 // And now the list of changes.
938 par.addChangesToToc(dit, buffer(), doing_output, backend);
943 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
944 DocIterator const & dit,
946 TocBackend & backend) const
948 Paragraph const & par = paragraphs()[pit];
949 TocBuilder & b = backend.builder(par.layout().tocType());
950 docstring const label = par.labelString();
951 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
952 return text().lastInSequence(pit);
956 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
957 TocBackend & backend) const
959 Paragraph const & par = paragraphs()[start];
960 TocBuilder & b = backend.builder(par.layout().tocType());
961 if (par.layout().isTocCaption()) {
963 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
970 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
972 if (buffer().isClean())
973 return Inset::notifyCursorLeaves(old, cur);
975 // find text inset in old cursor
976 Cursor insetCur = old;
977 int scriptSlice = insetCur.find(this);
978 // we can try to continue here. returning true means
979 // the cursor is "now" invalid. which it was.
980 LASSERT(scriptSlice != -1, return true);
981 insetCur.cutOff(scriptSlice);
982 LASSERT(&insetCur.inset() == this, return true);
984 // update the old paragraph's words
985 insetCur.paragraph().updateWords();
987 return Inset::notifyCursorLeaves(old, cur);
991 bool InsetText::completionSupported(Cursor const & cur) const
993 //LASSERT(&cur.bv().cursor().inset() == this, return false);
994 return text_.completionSupported(cur);
998 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1000 return completionSupported(cur);
1004 bool InsetText::automaticInlineCompletion() const
1006 return lyxrc.completion_inline_text;
1010 bool InsetText::automaticPopupCompletion() const
1012 return lyxrc.completion_popup_text;
1016 bool InsetText::showCompletionCursor() const
1018 return lyxrc.completion_cursor_text;
1022 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1024 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1028 docstring InsetText::completionPrefix(Cursor const & cur) const
1030 if (!completionSupported(cur))
1032 return text_.completionPrefix(cur);
1036 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1039 if (!completionSupported(cur))
1042 return text_.insertCompletion(cur, s, finished);
1046 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1047 Dimension & dim) const
1049 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1050 tm.completionPosAndDim(cur, x, y, dim);
1054 string InsetText::contextMenu(BufferView const &, int, int) const
1056 string context_menu = contextMenuName();
1057 if (context_menu != InsetText::contextMenuName())
1058 context_menu += ";" + InsetText::contextMenuName();
1059 return context_menu;
1063 string InsetText::contextMenuName() const
1065 return "context-edit";
1069 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1071 OutputParams rp(&buffer().params().encoding());
1072 rp.for_tooltip = true;
1073 odocstringstream oss;
1076 ParagraphList::const_iterator beg = paragraphs().begin();
1077 ParagraphList::const_iterator end = paragraphs().end();
1078 ParagraphList::const_iterator it = beg;
1079 bool ref_printed = false;
1081 for (; it != end; ++it) {
1084 if ((*it).isRTL(buffer().params()))
1085 oss << "<div dir=\"rtl\">";
1086 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1087 if ((*it).isRTL(buffer().params()))
1089 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1092 docstring str = oss.str();
1093 support::truncateWithEllipsis(str, len);
1098 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1100 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1104 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1106 // Nested cprotect content needs \cprotect
1108 if (producesOutput() && hasCProtectContent(fragile))
1111 // Environments generally need cprotection in fragile context
1112 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1115 if (!getLayout().needsCProtect())
1118 // Environments and "no latex" types (e.g., knitr chunks)
1119 // need cprotection regardless the content
1120 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1123 // If the inset does not produce output (e.g. Note or Branch),
1124 // we can ignore the contained paragraphs
1125 if (!producesOutput())
1128 // Commands need cprotection if they contain specific chars
1129 int const nchars_escape = 9;
1130 static char_type const chars_escape[nchars_escape] = {
1131 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1133 ParagraphList const & pars = paragraphs();
1134 pit_type pend = pit_type(paragraphs().size());
1136 for (pit_type pit = 0; pit != pend; ++pit) {
1137 Paragraph const & par = pars[size_type(pit)];
1138 if (par.needsCProtection(fragile))
1140 docstring const par_str = par.asString();
1141 for (int k = 0; k < nchars_escape; k++) {
1142 if (contains(par_str, chars_escape[k]))