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 bool InsetText::isChanged() const
415 ParagraphList::const_iterator pit = paragraphs().begin();
416 ParagraphList::const_iterator end = paragraphs().end();
417 for (; pit != end; ++pit) {
418 if (pit->isChanged())
425 void InsetText::setChange(Change const & change)
427 ParagraphList::iterator pit = paragraphs().begin();
428 ParagraphList::iterator end = paragraphs().end();
429 for (; pit != end; ++pit) {
430 pit->setChange(change);
435 void InsetText::acceptChanges()
437 text_.acceptChanges();
441 void InsetText::rejectChanges()
443 text_.rejectChanges();
447 void InsetText::validate(LaTeXFeatures & features) const
449 features.useInsetLayout(getLayout());
450 for (Paragraph const & p : paragraphs())
451 p.validate(features);
455 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
457 // This implements the standard way of handling the LaTeX
458 // output of a text inset, either a command or an
459 // environment. Standard collapsible insets should not
460 // redefine this, non-standard ones may call this.
461 InsetLayout const & il = getLayout();
462 if (il.forceOwnlines())
464 bool needendgroup = false;
465 if (!il.latexname().empty()) {
466 if (il.latextype() == InsetLayout::COMMAND) {
468 // FIXME \protect should only be used for fragile
469 // commands, but we do not provide this information yet.
470 if (hasCProtectContent(runparams.moving_arg)) {
471 if (contains(runparams.active_chars, '^')) {
472 // cprotect relies on ^ being on catcode 7
473 os << "\\begingroup\\catcode`\\^=7";
477 } else if (runparams.moving_arg)
479 os << '\\' << from_utf8(il.latexname());
480 if (!il.latexargs().empty())
481 getArgs(os, runparams);
482 if (!il.latexparam().empty())
483 os << from_utf8(il.latexparam());
485 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
490 if (runparams.lastid != -1)
491 os.texrow().start(runparams.lastid,
493 os << "\\begin{" << from_utf8(il.latexname()) << "}";
494 if (!il.latexargs().empty())
495 getArgs(os, runparams);
496 if (!il.latexparam().empty())
497 os << from_utf8(il.latexparam());
501 if (!il.latexargs().empty())
502 getArgs(os, runparams);
503 if (!il.latexparam().empty())
504 os << from_utf8(il.latexparam());
507 if (!il.leftdelim().empty())
508 os << il.leftdelim();
510 OutputParams rp = runparams;
513 if (il.isNeedProtect())
514 rp.moving_arg = true;
515 if (il.isNeedMBoxProtect())
517 if (!il.passThruChars().empty())
518 rp.pass_thru_chars += il.passThruChars();
519 if (!il.newlineCmd().empty())
520 rp.newlinecmd = il.newlineCmd();
522 rp.par_end = paragraphs().size();
524 // Output the contents of the inset
525 latexParagraphs(buffer(), text_, os, rp);
526 runparams.encoding = rp.encoding;
527 // Pass the post_macros upstream
528 runparams.post_macro = rp.post_macro;
530 if (!il.rightdelim().empty())
531 os << il.rightdelim();
533 if (!il.latexname().empty()) {
534 if (il.latextype() == InsetLayout::COMMAND) {
536 if (!il.postcommandargs().empty())
537 getArgs(os, runparams, true);
540 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
541 // A comment environment doesn't need a % before \n\end
542 if (il.isDisplay() || runparams.inComment)
546 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
548 os.protectSpace(true);
551 if (il.forceOwnlines())
556 int InsetText::plaintext(odocstringstream & os,
557 OutputParams const & runparams, size_t max_length) const
559 ParagraphList::const_iterator beg = paragraphs().begin();
560 ParagraphList::const_iterator end = paragraphs().end();
561 ParagraphList::const_iterator it = beg;
562 bool ref_printed = false;
564 for (; it != end; ++it) {
567 if (runparams.linelen > 0)
570 odocstringstream oss;
571 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
572 docstring const str = oss.str();
574 // FIXME: len is not computed fully correctly; in principle,
575 // we have to count the characters after the last '\n'
577 if (os.str().size() >= max_length)
585 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
587 ParagraphList::const_iterator const beg = paragraphs().begin();
590 sgml::openTag(os, getLayout().latexname(),
591 beg->getID(buffer(), runparams) + getLayout().latexparam());
593 docbookParagraphs(text_, buffer(), os, runparams);
596 sgml::closeTag(os, getLayout().latexname());
602 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
604 return insetAsXHTML(xs, runparams, WriteEverything);
609 // There are cases where we may need to close open fonts and such
610 // and then re-open them when we are done. This would be the case, e.g.,
611 // if we were otherwise about to write:
612 // <em>word <div class='foot'>footnote text.</div> emph</em>
613 // The problem isn't so much that the footnote text will get emphasized:
614 // we can handle that with CSS. The problem is that this is invalid XHTML.
615 // One solution would be to make the footnote <span>, but the problem is
616 // completely general, and so we'd have to make absolutely everything into
617 // span. What I think will work is to check if we're about to write "div" and,
618 // if so, try to close fonts, etc.
619 // There are probably limits to how well we can do here, though, and we will
620 // have to rely upon users not putting footnotes inside noun-type insets.
621 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
622 XHTMLOptions opts) const
624 // we will always want to output all our paragraphs when we are
626 OutputParams runparams = rp;
627 runparams.par_begin = 0;
628 runparams.par_end = text().paragraphs().size();
631 xs.startDivision(false);
632 xhtmlParagraphs(text_, buffer(), xs, runparams);
637 InsetLayout const & il = getLayout();
638 if (opts & WriteOuterTag)
639 xs << html::StartTag(il.htmltag(), il.htmlattr());
641 if ((opts & WriteLabel) && !il.counter().empty()) {
642 BufferParams const & bp = buffer().masterBuffer()->params();
643 Counters & cntrs = bp.documentClass().counters();
644 cntrs.step(il.counter(), OutputUpdate);
645 // FIXME: translate to paragraph language
646 if (!il.htmllabel().empty()) {
647 docstring const lbl =
648 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
649 // FIXME is this check necessary?
651 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
653 xs << html::EndTag(il.htmllabeltag());
658 if (opts & WriteInnerTag)
659 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
661 // we will eventually lose information about the containing inset
662 if (!allowMultiPar() || opts == JustText)
663 runparams.html_make_pars = false;
665 runparams.pass_thru = true;
667 xs.startDivision(false);
668 xhtmlParagraphs(text_, buffer(), xs, runparams);
671 if (opts & WriteInnerTag)
672 xs << html::EndTag(il.htmlinnertag());
674 if (opts & WriteOuterTag)
675 xs << html::EndTag(il.htmltag());
681 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
682 bool const post) const
684 OutputParams runparams = runparams_in;
685 runparams.local_font =
686 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
688 runparams.pass_thru = true;
690 latexArgInsetsForParent(paragraphs(), os, runparams,
691 getLayout().postcommandargs(), "post:");
693 latexArgInsetsForParent(paragraphs(), os, runparams,
694 getLayout().latexargs());
698 void InsetText::cursorPos(BufferView const & bv,
699 CursorSlice const & sl, bool boundary, int & x, int & y) const
701 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
702 y = bv.textMetrics(&text_).cursorY(sl, boundary);
706 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
709 Paragraph & first = paragraphs().front();
710 for (unsigned int i = 0; i < data.length(); ++i)
711 first.insertChar(i, data[i], font, trackChanges);
715 void InsetText::setDrawFrame(bool flag)
721 ColorCode InsetText::frameColor() const
727 void InsetText::setFrameColor(ColorCode col)
733 void InsetText::appendParagraphs(ParagraphList & plist)
735 // There is little we can do here to keep track of changes.
736 // As of 2006/10/20, appendParagraphs is used exclusively by
737 // LyXTabular::setMultiColumn. In this context, the paragraph break
738 // is lost irreversibly and the appended text doesn't really change
740 ParagraphList & pl = paragraphs();
742 ParagraphList::iterator pit = plist.begin();
743 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
745 mergeParagraph(buffer().params(), pl,
746 distance(pl.begin(), ins) - 1);
748 for_each(pit, plist.end(),
749 bind(&ParagraphList::push_back, ref(pl), _1));
753 void InsetText::addPreview(DocIterator const & text_inset_pos,
754 PreviewLoader & loader) const
756 ParagraphList::const_iterator pit = paragraphs().begin();
757 ParagraphList::const_iterator pend = paragraphs().end();
760 DocIterator inset_pos = text_inset_pos;
761 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
763 for (; pit != pend; ++pit, ++pidx) {
764 InsetList::const_iterator it = pit->insetList().begin();
765 InsetList::const_iterator end = pit->insetList().end();
766 inset_pos.pit() = pidx;
767 for (; it != end; ++it) {
768 inset_pos.pos() = it->pos;
769 it->inset->addPreview(inset_pos, loader);
775 ParagraphList const & InsetText::paragraphs() const
777 return text_.paragraphs();
781 ParagraphList & InsetText::paragraphs()
783 return text_.paragraphs();
787 bool InsetText::hasCProtectContent(bool fragile) const
789 fragile |= getLayout().isNeedProtect();
790 ParagraphList const & pars = paragraphs();
791 pit_type pend = pit_type(paragraphs().size());
792 for (pit_type pit = 0; pit != pend; ++pit) {
793 Paragraph const & par = pars[size_type(pit)];
794 if (par.needsCProtection(fragile))
801 bool InsetText::insetAllowed(InsetCode code) const
804 // Arguments and (plain) quotes are also allowed in PassThru insets
809 return !isPassThru();
814 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
816 ParIterator it2 = it;
818 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
819 if (producesOutput()) {
820 InsetLayout const & il = getLayout();
821 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
822 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
824 // LYXERR0("Entering " << name());
825 cnt.clearLastLayout();
826 // FIXME cnt.saveLastCounter()?
828 buffer().updateBuffer(it2, utype);
830 // LYXERR0("Exiting " << name());
831 cnt.restoreLastLayout();
832 // FIXME cnt.restoreLastCounter()?
835 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
836 // Note that we do not need to call:
837 // tclass.counters().clearLastLayout()
838 // since we are saving and restoring the existing counters, etc.
839 Counters savecnt = tclass.counters();
840 tclass.counters().reset();
841 // we need float information even in note insets (#9760)
842 tclass.counters().current_float(savecnt.current_float());
843 tclass.counters().isSubfloat(savecnt.isSubfloat());
844 buffer().updateBuffer(it2, utype);
845 tclass.counters() = move(savecnt);
850 void InsetText::toString(odocstream & os) const
852 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
856 void InsetText::forOutliner(docstring & os, size_t const maxlen,
857 bool const shorten) const
859 if (!getLayout().isInToc())
861 text().forOutliner(os, maxlen, shorten);
865 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
866 UpdateType utype, TocBackend & backend) const
868 DocIterator dit = cdit;
869 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
870 iterateForToc(dit, output_active, utype, backend);
874 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
875 UpdateType utype, TocBackend & backend) const
877 DocIterator dit = cdit;
878 // This also ensures that any document has a table of contents
879 shared_ptr<Toc> toc = backend.toc("tableofcontents");
881 BufferParams const & bufparams = buffer_->params();
882 int const min_toclevel = bufparams.documentClass().min_toclevel();
883 // we really should have done this before we got here, but it
884 // can't hurt too much to do it again
885 bool const doing_output = output_active && producesOutput();
887 // For each paragraph,
888 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
889 // paragraphs as needed.
890 // * Traverse its insets and let them add their toc items
891 // * Compute the main table of contents (this is hardcoded)
892 // * Add the list of changes
893 ParagraphList const & pars = paragraphs();
894 pit_type pend = paragraphs().size();
895 // Record pairs {start,end} of where a toc item was opened for a paragraph
896 // and where it must be closed
897 stack<pair<pit_type, pit_type>> addtotoc_stack;
899 for (pit_type pit = 0; pit != pend; ++pit) {
900 Paragraph const & par = pars[pit];
904 // Custom AddToToc in paragraph layouts (i.e. theorems)
905 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
907 openAddToTocForParagraph(pit, dit, output_active, backend);
908 addtotoc_stack.push({pit, end});
911 // If we find an InsetArgument that is supposed to provide the TOC caption,
912 // we'll save it for use later.
913 InsetArgument const * arginset = nullptr;
914 for (auto const & table : par.insetList()) {
915 dit.pos() = table.pos;
916 table.inset->addToToc(dit, doing_output, utype, backend);
917 if (InsetArgument const * x = table.inset->asInsetArgument())
918 if (x->isTocCaption())
922 // End custom AddToToc in paragraph layouts
923 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
924 // execute the closing function
925 closeAddToTocForParagraph(addtotoc_stack.top().first,
926 addtotoc_stack.top().second, backend);
927 addtotoc_stack.pop();
930 // now the toc entry for the paragraph in the main table of contents
931 int const toclevel = text().getTocLevel(pit);
932 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
933 // insert this into the table of contents
935 int const length = (doing_output && utype == OutputUpdate) ?
936 INT_MAX : TOC_ENTRY_LENGTH;
938 tocstring = par.labelString();
939 if (!tocstring.empty())
941 arginset->text().forOutliner(tocstring, length);
943 par.forOutliner(tocstring, length);
945 toc->push_back(TocItem(dit, toclevel - min_toclevel,
946 tocstring, doing_output));
949 // And now the list of changes.
950 par.addChangesToToc(dit, buffer(), doing_output, backend);
955 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
956 DocIterator const & dit,
958 TocBackend & backend) const
960 Paragraph const & par = paragraphs()[pit];
961 TocBuilder & b = backend.builder(par.layout().tocType());
962 docstring const label = par.labelString();
963 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
964 return text().lastInSequence(pit);
968 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
969 TocBackend & backend) const
971 Paragraph const & par = paragraphs()[start];
972 TocBuilder & b = backend.builder(par.layout().tocType());
973 if (par.layout().isTocCaption()) {
975 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
982 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
984 if (buffer().isClean())
985 return Inset::notifyCursorLeaves(old, cur);
987 // find text inset in old cursor
988 Cursor insetCur = old;
989 int scriptSlice = insetCur.find(this);
990 // we can try to continue here. returning true means
991 // the cursor is "now" invalid. which it was.
992 LASSERT(scriptSlice != -1, return true);
993 insetCur.cutOff(scriptSlice);
994 LASSERT(&insetCur.inset() == this, return true);
996 // update the old paragraph's words
997 insetCur.paragraph().updateWords();
999 return Inset::notifyCursorLeaves(old, cur);
1003 bool InsetText::completionSupported(Cursor const & cur) const
1005 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1006 return text_.completionSupported(cur);
1010 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1012 return completionSupported(cur);
1016 bool InsetText::automaticInlineCompletion() const
1018 return lyxrc.completion_inline_text;
1022 bool InsetText::automaticPopupCompletion() const
1024 return lyxrc.completion_popup_text;
1028 bool InsetText::showCompletionCursor() const
1030 return lyxrc.completion_cursor_text;
1034 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1036 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1040 docstring InsetText::completionPrefix(Cursor const & cur) const
1042 if (!completionSupported(cur))
1044 return text_.completionPrefix(cur);
1048 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1051 if (!completionSupported(cur))
1054 return text_.insertCompletion(cur, s, finished);
1058 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1059 Dimension & dim) const
1061 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1062 tm.completionPosAndDim(cur, x, y, dim);
1066 string InsetText::contextMenu(BufferView const &, int, int) const
1068 string context_menu = contextMenuName();
1069 if (context_menu != InsetText::contextMenuName())
1070 context_menu += ";" + InsetText::contextMenuName();
1071 return context_menu;
1075 string InsetText::contextMenuName() const
1077 return "context-edit";
1081 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1083 OutputParams rp(&buffer().params().encoding());
1084 rp.for_tooltip = true;
1085 odocstringstream oss;
1088 ParagraphList::const_iterator beg = paragraphs().begin();
1089 ParagraphList::const_iterator end = paragraphs().end();
1090 ParagraphList::const_iterator it = beg;
1091 bool ref_printed = false;
1093 for (; it != end; ++it) {
1096 if ((*it).isRTL(buffer().params()))
1097 oss << "<div dir=\"rtl\">";
1098 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1099 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1102 docstring str = oss.str();
1104 str += from_ascii("\n\n") + _("[contains tracked changes]");
1105 support::truncateWithEllipsis(str, len);
1110 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1112 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1116 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1118 // Nested cprotect content needs \cprotect
1120 if (producesOutput() && hasCProtectContent(fragile))
1123 // Environments generally need cprotection in fragile context
1124 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1127 if (!getLayout().needsCProtect())
1130 // Environments and "no latex" types (e.g., knitr chunks)
1131 // need cprotection regardless the content
1132 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1135 // If the inset does not produce output (e.g. Note or Branch),
1136 // we can ignore the contained paragraphs
1137 if (!producesOutput())
1140 // Commands need cprotection if they contain specific chars
1141 int const nchars_escape = 9;
1142 static char_type const chars_escape[nchars_escape] = {
1143 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1145 ParagraphList const & pars = paragraphs();
1146 pit_type pend = pit_type(paragraphs().size());
1148 for (pit_type pit = 0; pit != pend; ++pit) {
1149 Paragraph const & par = pars[size_type(pit)];
1150 if (par.needsCProtection(fragile))
1152 docstring const par_str = par.asString();
1153 for (int k = 0; k < nchars_escape; k++) {
1154 if (contains(par_str, chars_escape[k]))