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), is_changed_(false), frame_color_(Color_insetframe),
83 text_(this, type == DefaultLayout)
88 InsetText::InsetText(InsetText const & in)
89 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
90 frame_color_(in.frame_color_),
96 void InsetText::setBuffer(Buffer & buf)
98 ParagraphList::iterator end = paragraphs().end();
99 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100 it->setInsetBuffers(buf);
101 Inset::setBuffer(buf);
105 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
107 text_.setMacrocontextPosition(pos);
109 ParagraphList::const_iterator pit = paragraphs().begin();
110 ParagraphList::const_iterator pend = paragraphs().end();
111 for (; pit != pend; ++pit) {
112 InsetList::const_iterator iit = pit->insetList().begin();
113 InsetList::const_iterator end = pit->insetList().end();
114 for (; iit != end; ++iit) {
115 if (InsetText * txt = iit->inset->asInsetText()) {
116 DocIterator ppos(pos);
117 ppos.push_back(CursorSlice(*txt));
118 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
125 void InsetText::clear()
127 ParagraphList & pars = paragraphs();
128 LBUFERR(!pars.empty());
130 // This is a gross hack...
131 Layout const & old_layout = pars.begin()->layout();
134 pars.push_back(Paragraph());
135 pars.begin()->setInsetOwner(this);
136 pars.begin()->setLayout(old_layout);
140 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
142 TextMetrics const & tm = bv.textMetrics(&text_);
143 Dimension dim = tm.dim();
144 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
145 dim.des += TEXT_TO_INSET_OFFSET;
146 dim.asc += TEXT_TO_INSET_OFFSET;
151 void InsetText::write(ostream & os) const
158 void InsetText::read(Lexer & lex)
162 // delete the initial paragraph
163 Paragraph oldpar = *paragraphs().begin();
164 paragraphs().clear();
166 lex.setContext("InsetText::read");
167 bool res = text_.read(lex, errorList, this);
170 lex.printError("Missing \\end_inset at this point. ");
173 // ensure we have at least one paragraph.
174 if (paragraphs().empty())
175 paragraphs().push_back(oldpar);
176 // Force default font, if so requested
177 // This avoids paragraphs in buffer language that would have a
178 // foreign language after a document language change, and it ensures
179 // that all new text in ERT and similar gets the "latex" language,
180 // since new text inherits the language from the last position of the
181 // existing text. As a side effect this makes us also robust against
182 // bugs in LyX that might lead to font changes in ERT in .lyx files.
187 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193 // Hand font through to contained lyxtext:
194 tm.font_.fontInfo() = mi.base.font;
195 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
197 // This can happen when a layout has a left and right margin,
198 // and the view is made very narrow. We can't do better than
199 // to draw it partly out of view (bug 5890).
200 if (mi.base.textwidth < 1)
201 mi.base.textwidth = 1;
204 tm.metrics(mi, dim, mi.base.textwidth);
207 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
208 dim.asc += TEXT_TO_INSET_OFFSET;
209 dim.des += TEXT_TO_INSET_OFFSET;
210 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
214 void InsetText::draw(PainterInfo & pi, int x, int y) const
216 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
218 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
219 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
220 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
221 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
222 bool change_drawn = false;
224 pi.pain.fillRectangle(xframe, yframe, w, h,
225 pi.backgroundColor(this));
228 Changer dummy = make_change(pi.background_color,
229 pi.backgroundColor(this, false));
230 // The change tracking cue must not be inherited
231 Changer dummy2 = make_change(pi.change_, Change());
232 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
236 // Change color of the frame in tracked changes, like for tabulars.
237 // Only do so if the color is not custom. But do so even if RowPainter
238 // handles the strike-through already.
240 if (pi.change_.changed()
241 // Originally, these are the colors with role Text, from role() in
242 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
243 // types, and also maybe it need not match in the future.
244 && (frameColor() == Color_foreground
245 || frameColor() == Color_cursor
246 || frameColor() == Color_preview
247 || frameColor() == Color_tabularline
248 || frameColor() == Color_previewframe)) {
249 c = pi.change_.color();
253 pi.pain.rectangle(xframe, yframe, w, h, c);
256 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
257 // Do not draw the change tracking cue if already done by RowPainter and
258 // do not draw the cue for INSERTED if the information is already in the
259 // color of the frame
260 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
264 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
266 pit_type const pit = front ? 0 : paragraphs().size() - 1;
267 pos_type pos = front ? 0 : paragraphs().back().size();
269 // if visual information is not to be ignored, move to extreme right/left
270 if (entry_from != ENTRY_DIRECTION_IGNORE) {
271 Cursor temp_cur = cur;
272 temp_cur.pit() = pit;
273 temp_cur.pos() = pos;
274 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
275 pos = temp_cur.pos();
278 cur.top().setPitPos(pit, pos);
283 Inset * InsetText::editXY(Cursor & cur, int x, int y)
285 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
289 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
291 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
293 // See bug #9042, for instance.
295 // Force any new text to latex_language FIXME: This
296 // should only be necessary in constructor, but new
297 // paragraphs that are created by pressing enter at
298 // the start of an existing paragraph get the buffer
299 // language and not latex_language, so we take this
300 // brute force approach.
301 cur.current_font.setLanguage(latex_language);
302 cur.real_current_font.setLanguage(latex_language);
305 switch (cmd.action()) {
307 case LFUN_CLIPBOARD_PASTE:
308 case LFUN_SELECTION_PASTE:
309 case LFUN_PRIMARY_SELECTION_PASTE:
310 text_.dispatch(cur, cmd);
311 // If we we can only store plain text, we must reset all
313 // FIXME: Change only the pasted paragraphs
317 case LFUN_INSET_DISSOLVE: {
318 bool const main_inset = text_.isMainText();
319 bool const target_inset = cmd.argument().empty()
320 || cmd.getArg(0) == insetName(lyxCode());
322 if (!main_inset && target_inset) {
323 // Text::dissolveInset assumes that the cursor
324 // is inside the Inset.
325 if (&cur.inset() != this)
326 cur.pushBackward(*this);
327 cur.beginUndoGroup();
328 text_.dispatch(cur, cmd);
336 text_.dispatch(cur, cmd);
339 if (!cur.result().dispatched())
340 Inset::doDispatch(cur, cmd);
344 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
345 FuncStatus & status) const
347 switch (cmd.action()) {
348 case LFUN_INSET_DISSOLVE: {
349 bool const main_inset = text_.isMainText();
350 bool const target_inset = cmd.argument().empty()
351 || cmd.getArg(0) == insetName(lyxCode());
354 status.setEnabled(!main_inset);
358 case LFUN_ARGUMENT_INSERT: {
359 string const arg = cmd.getArg(0);
361 status.setEnabled(false);
364 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
365 return text_.getStatus(cur, cmd, status);
367 Layout::LaTeXArgMap args = getLayout().args();
368 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
369 if (lait != args.end()) {
370 status.setEnabled(true);
371 for (Paragraph const & par : paragraphs())
372 for (auto const & table : par.insetList())
373 if (InsetArgument const * ins = table.inset->asInsetArgument())
374 if (ins->name() == arg) {
375 // we have this already
376 status.setEnabled(false);
380 status.setEnabled(false);
385 // Dispatch only to text_ if the cursor is inside
386 // the text_. It is not for context menus (bug 5797).
388 if (cur.text() == &text_)
389 ret = text_.getStatus(cur, cmd, status);
392 ret = Inset::getStatus(cur, cmd, status);
398 void InsetText::fixParagraphsFont()
400 Font font(inherit_font, buffer().params().language);
401 font.setLanguage(latex_language);
402 ParagraphList::iterator par = paragraphs().begin();
403 ParagraphList::iterator const end = paragraphs().end();
405 if (par->isPassThru())
406 par->resetFonts(font);
407 if (!par->allowParagraphCustomization())
408 par->params().clear();
414 // bool InsetText::isChanged() const
416 // ParagraphList::const_iterator pit = paragraphs().begin();
417 // ParagraphList::const_iterator end = paragraphs().end();
418 // for (; pit != end; ++pit) {
419 // if (pit->isChanged())
426 void InsetText::setChange(Change const & change)
428 ParagraphList::iterator pit = paragraphs().begin();
429 ParagraphList::iterator end = paragraphs().end();
430 for (; pit != end; ++pit) {
431 pit->setChange(change);
436 void InsetText::acceptChanges()
438 text_.acceptChanges();
442 void InsetText::rejectChanges()
444 text_.rejectChanges();
448 void InsetText::validate(LaTeXFeatures & features) const
450 features.useInsetLayout(getLayout());
451 for (Paragraph const & p : paragraphs())
452 p.validate(features);
456 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
458 // This implements the standard way of handling the LaTeX
459 // output of a text inset, either a command or an
460 // environment. Standard collapsible insets should not
461 // redefine this, non-standard ones may call this.
462 InsetLayout const & il = getLayout();
463 if (il.forceOwnlines())
465 bool needendgroup = false;
466 if (!il.latexname().empty()) {
467 if (il.latextype() == InsetLayout::COMMAND) {
469 // FIXME \protect should only be used for fragile
470 // commands, but we do not provide this information yet.
471 if (hasCProtectContent(runparams.moving_arg)) {
472 if (contains(runparams.active_chars, '^')) {
473 // cprotect relies on ^ being on catcode 7
474 os << "\\begingroup\\catcode`\\^=7";
478 } else if (runparams.moving_arg)
480 os << '\\' << from_utf8(il.latexname());
481 if (!il.latexargs().empty())
482 getArgs(os, runparams);
483 if (!il.latexparam().empty())
484 os << from_utf8(il.latexparam());
486 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
491 if (runparams.lastid != -1)
492 os.texrow().start(runparams.lastid,
494 os << "\\begin{" << from_utf8(il.latexname()) << "}";
495 if (!il.latexargs().empty())
496 getArgs(os, runparams);
497 if (!il.latexparam().empty())
498 os << from_utf8(il.latexparam());
502 if (!il.latexargs().empty())
503 getArgs(os, runparams);
504 if (!il.latexparam().empty())
505 os << from_utf8(il.latexparam());
508 if (!il.leftdelim().empty())
509 os << il.leftdelim();
511 OutputParams rp = runparams;
514 if (il.isNeedProtect())
515 rp.moving_arg = true;
516 if (il.isNeedMBoxProtect())
518 if (!il.passThruChars().empty())
519 rp.pass_thru_chars += il.passThruChars();
520 if (!il.newlineCmd().empty())
521 rp.newlinecmd = il.newlineCmd();
523 rp.par_end = paragraphs().size();
525 // Output the contents of the inset
526 latexParagraphs(buffer(), text_, os, rp);
527 runparams.encoding = rp.encoding;
528 // Pass the post_macros upstream
529 runparams.post_macro = rp.post_macro;
531 if (!il.rightdelim().empty())
532 os << il.rightdelim();
534 if (!il.latexname().empty()) {
535 if (il.latextype() == InsetLayout::COMMAND) {
537 if (!il.postcommandargs().empty())
538 getArgs(os, runparams, true);
541 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
542 // A comment environment doesn't need a % before \n\end
543 if (il.isDisplay() || runparams.inComment)
547 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
549 os.protectSpace(true);
552 if (il.forceOwnlines())
557 int InsetText::plaintext(odocstringstream & os,
558 OutputParams const & runparams, size_t max_length) const
560 ParagraphList::const_iterator beg = paragraphs().begin();
561 ParagraphList::const_iterator end = paragraphs().end();
562 ParagraphList::const_iterator it = beg;
563 bool ref_printed = false;
565 for (; it != end; ++it) {
568 if (runparams.linelen > 0)
571 odocstringstream oss;
572 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
573 docstring const str = oss.str();
575 // FIXME: len is not computed fully correctly; in principle,
576 // we have to count the characters after the last '\n'
578 if (os.str().size() >= max_length)
586 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
588 ParagraphList::const_iterator const beg = paragraphs().begin();
591 sgml::openTag(os, getLayout().latexname(),
592 beg->getID(buffer(), runparams) + getLayout().latexparam());
594 docbookParagraphs(text_, buffer(), os, runparams);
597 sgml::closeTag(os, getLayout().latexname());
603 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
605 return insetAsXHTML(xs, runparams, WriteEverything);
610 // There are cases where we may need to close open fonts and such
611 // and then re-open them when we are done. This would be the case, e.g.,
612 // if we were otherwise about to write:
613 // <em>word <div class='foot'>footnote text.</div> emph</em>
614 // The problem isn't so much that the footnote text will get emphasized:
615 // we can handle that with CSS. The problem is that this is invalid XHTML.
616 // One solution would be to make the footnote <span>, but the problem is
617 // completely general, and so we'd have to make absolutely everything into
618 // span. What I think will work is to check if we're about to write "div" and,
619 // if so, try to close fonts, etc.
620 // There are probably limits to how well we can do here, though, and we will
621 // have to rely upon users not putting footnotes inside noun-type insets.
622 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
623 XHTMLOptions opts) const
625 // we will always want to output all our paragraphs when we are
627 OutputParams runparams = rp;
628 runparams.par_begin = 0;
629 runparams.par_end = text().paragraphs().size();
632 xs.startDivision(false);
633 xhtmlParagraphs(text_, buffer(), xs, runparams);
638 InsetLayout const & il = getLayout();
639 if (opts & WriteOuterTag)
640 xs << html::StartTag(il.htmltag(), il.htmlattr());
642 if ((opts & WriteLabel) && !il.counter().empty()) {
643 BufferParams const & bp = buffer().masterBuffer()->params();
644 Counters & cntrs = bp.documentClass().counters();
645 cntrs.step(il.counter(), OutputUpdate);
646 // FIXME: translate to paragraph language
647 if (!il.htmllabel().empty()) {
648 docstring const lbl =
649 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
650 // FIXME is this check necessary?
652 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
654 xs << html::EndTag(il.htmllabeltag());
659 if (opts & WriteInnerTag)
660 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
662 // we will eventually lose information about the containing inset
663 if (!allowMultiPar() || opts == JustText)
664 runparams.html_make_pars = false;
666 runparams.pass_thru = true;
668 xs.startDivision(false);
669 xhtmlParagraphs(text_, buffer(), xs, runparams);
672 if (opts & WriteInnerTag)
673 xs << html::EndTag(il.htmlinnertag());
675 if (opts & WriteOuterTag)
676 xs << html::EndTag(il.htmltag());
682 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
683 bool const post) const
685 OutputParams runparams = runparams_in;
686 runparams.local_font =
687 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
689 runparams.pass_thru = true;
691 latexArgInsetsForParent(paragraphs(), os, runparams,
692 getLayout().postcommandargs(), "post:");
694 latexArgInsetsForParent(paragraphs(), os, runparams,
695 getLayout().latexargs());
699 void InsetText::cursorPos(BufferView const & bv,
700 CursorSlice const & sl, bool boundary, int & x, int & y) const
702 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
703 y = bv.textMetrics(&text_).cursorY(sl, boundary);
707 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
710 Paragraph & first = paragraphs().front();
711 for (unsigned int i = 0; i < data.length(); ++i)
712 first.insertChar(i, data[i], font, trackChanges);
716 void InsetText::setDrawFrame(bool flag)
722 ColorCode InsetText::frameColor() const
728 void InsetText::setFrameColor(ColorCode col)
734 void InsetText::appendParagraphs(ParagraphList & plist)
736 // There is little we can do here to keep track of changes.
737 // As of 2006/10/20, appendParagraphs is used exclusively by
738 // LyXTabular::setMultiColumn. In this context, the paragraph break
739 // is lost irreversibly and the appended text doesn't really change
741 ParagraphList & pl = paragraphs();
743 ParagraphList::iterator pit = plist.begin();
744 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
746 mergeParagraph(buffer().params(), pl,
747 distance(pl.begin(), ins) - 1);
749 for_each(pit, plist.end(),
750 bind(&ParagraphList::push_back, ref(pl), _1));
754 void InsetText::addPreview(DocIterator const & text_inset_pos,
755 PreviewLoader & loader) const
757 ParagraphList::const_iterator pit = paragraphs().begin();
758 ParagraphList::const_iterator pend = paragraphs().end();
761 DocIterator inset_pos = text_inset_pos;
762 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
764 for (; pit != pend; ++pit, ++pidx) {
765 InsetList::const_iterator it = pit->insetList().begin();
766 InsetList::const_iterator end = pit->insetList().end();
767 inset_pos.pit() = pidx;
768 for (; it != end; ++it) {
769 inset_pos.pos() = it->pos;
770 it->inset->addPreview(inset_pos, loader);
776 ParagraphList const & InsetText::paragraphs() const
778 return text_.paragraphs();
782 ParagraphList & InsetText::paragraphs()
784 return text_.paragraphs();
788 bool InsetText::hasCProtectContent(bool fragile) const
790 fragile |= getLayout().isNeedProtect();
791 ParagraphList const & pars = paragraphs();
792 pit_type pend = pit_type(paragraphs().size());
793 for (pit_type pit = 0; pit != pend; ++pit) {
794 Paragraph const & par = pars[size_type(pit)];
795 if (par.needsCProtection(fragile))
802 bool InsetText::insetAllowed(InsetCode code) const
805 // Arguments and (plain) quotes are also allowed in PassThru insets
810 return !isPassThru();
815 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
817 ParIterator it2 = it;
819 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
820 if (producesOutput()) {
821 InsetLayout const & il = getLayout();
822 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
823 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
825 // LYXERR0("Entering " << name());
826 cnt.clearLastLayout();
827 // FIXME cnt.saveLastCounter()?
829 buffer().updateBuffer(it2, utype);
831 // LYXERR0("Exiting " << name());
832 cnt.restoreLastLayout();
833 // FIXME cnt.restoreLastCounter()?
836 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
837 // Note that we do not need to call:
838 // tclass.counters().clearLastLayout()
839 // since we are saving and restoring the existing counters, etc.
840 Counters savecnt = tclass.counters();
841 tclass.counters().reset();
842 // we need float information even in note insets (#9760)
843 tclass.counters().current_float(savecnt.current_float());
844 tclass.counters().isSubfloat(savecnt.isSubfloat());
845 buffer().updateBuffer(it2, utype);
846 tclass.counters() = move(savecnt);
851 void InsetText::toString(odocstream & os) const
853 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
857 void InsetText::forOutliner(docstring & os, size_t const maxlen,
858 bool const shorten) const
860 if (!getLayout().isInToc())
862 text().forOutliner(os, maxlen, shorten);
866 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
867 UpdateType utype, TocBackend & backend) const
869 DocIterator dit = cdit;
870 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
871 iterateForToc(dit, output_active, utype, backend);
875 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
876 UpdateType utype, TocBackend & backend) const
878 DocIterator dit = cdit;
879 // This also ensures that any document has a table of contents
880 shared_ptr<Toc> toc = backend.toc("tableofcontents");
882 BufferParams const & bufparams = buffer_->params();
883 int const min_toclevel = bufparams.documentClass().min_toclevel();
884 // we really should have done this before we got here, but it
885 // can't hurt too much to do it again
886 bool const doing_output = output_active && producesOutput();
888 // For each paragraph,
889 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
890 // paragraphs as needed.
891 // * Traverse its insets and let them add their toc items
892 // * Compute the main table of contents (this is hardcoded)
893 // * Add the list of changes
894 ParagraphList const & pars = paragraphs();
895 pit_type pend = paragraphs().size();
896 // Record pairs {start,end} of where a toc item was opened for a paragraph
897 // and where it must be closed
898 stack<pair<pit_type, pit_type>> addtotoc_stack;
900 for (pit_type pit = 0; pit != pend; ++pit) {
901 Paragraph const & par = pars[pit];
905 // Custom AddToToc in paragraph layouts (i.e. theorems)
906 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
908 openAddToTocForParagraph(pit, dit, output_active, backend);
909 addtotoc_stack.push({pit, end});
912 // If we find an InsetArgument that is supposed to provide the TOC caption,
913 // we'll save it for use later.
914 InsetArgument const * arginset = nullptr;
915 for (auto const & table : par.insetList()) {
916 dit.pos() = table.pos;
917 table.inset->addToToc(dit, doing_output, utype, backend);
918 if (InsetArgument const * x = table.inset->asInsetArgument())
919 if (x->isTocCaption())
923 // End custom AddToToc in paragraph layouts
924 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
925 // execute the closing function
926 closeAddToTocForParagraph(addtotoc_stack.top().first,
927 addtotoc_stack.top().second, backend);
928 addtotoc_stack.pop();
931 // now the toc entry for the paragraph in the main table of contents
932 int const toclevel = text().getTocLevel(pit);
933 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
934 // insert this into the table of contents
936 int const length = (doing_output && utype == OutputUpdate) ?
937 INT_MAX : TOC_ENTRY_LENGTH;
939 tocstring = par.labelString();
940 if (!tocstring.empty())
942 arginset->text().forOutliner(tocstring, length);
944 par.forOutliner(tocstring, length);
946 toc->push_back(TocItem(dit, toclevel - min_toclevel,
947 tocstring, doing_output));
950 // And now the list of changes.
951 par.addChangesToToc(dit, buffer(), doing_output, backend);
956 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
957 DocIterator const & dit,
959 TocBackend & backend) const
961 Paragraph const & par = paragraphs()[pit];
962 TocBuilder & b = backend.builder(par.layout().tocType());
963 docstring const label = par.labelString();
964 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
965 return text().lastInSequence(pit);
969 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
970 TocBackend & backend) const
972 Paragraph const & par = paragraphs()[start];
973 TocBuilder & b = backend.builder(par.layout().tocType());
974 if (par.layout().isTocCaption()) {
976 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
983 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
985 if (buffer().isClean())
986 return Inset::notifyCursorLeaves(old, cur);
988 // find text inset in old cursor
989 Cursor insetCur = old;
990 int scriptSlice = insetCur.find(this);
991 // we can try to continue here. returning true means
992 // the cursor is "now" invalid. which it was.
993 LASSERT(scriptSlice != -1, return true);
994 insetCur.cutOff(scriptSlice);
995 LASSERT(&insetCur.inset() == this, return true);
997 // update the old paragraph's words
998 insetCur.paragraph().updateWords();
1000 return Inset::notifyCursorLeaves(old, cur);
1004 bool InsetText::completionSupported(Cursor const & cur) const
1006 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1007 return text_.completionSupported(cur);
1011 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1013 return completionSupported(cur);
1017 bool InsetText::automaticInlineCompletion() const
1019 return lyxrc.completion_inline_text;
1023 bool InsetText::automaticPopupCompletion() const
1025 return lyxrc.completion_popup_text;
1029 bool InsetText::showCompletionCursor() const
1031 return lyxrc.completion_cursor_text;
1035 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1037 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1041 docstring InsetText::completionPrefix(Cursor const & cur) const
1043 if (!completionSupported(cur))
1045 return text_.completionPrefix(cur);
1049 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1052 if (!completionSupported(cur))
1055 return text_.insertCompletion(cur, s, finished);
1059 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1060 Dimension & dim) const
1062 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1063 tm.completionPosAndDim(cur, x, y, dim);
1067 string InsetText::contextMenu(BufferView const &, int, int) const
1069 string context_menu = contextMenuName();
1070 if (context_menu != InsetText::contextMenuName())
1071 context_menu += ";" + InsetText::contextMenuName();
1072 return context_menu;
1076 string InsetText::contextMenuName() const
1078 return "context-edit";
1082 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1084 OutputParams rp(&buffer().params().encoding());
1085 rp.for_tooltip = true;
1086 odocstringstream oss;
1089 ParagraphList::const_iterator beg = paragraphs().begin();
1090 ParagraphList::const_iterator end = paragraphs().end();
1091 ParagraphList::const_iterator it = beg;
1092 bool ref_printed = false;
1094 for (; it != end; ++it) {
1097 if ((*it).isRTL(buffer().params()))
1098 oss << "<div dir=\"rtl\">";
1099 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1100 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1103 docstring str = oss.str();
1105 str += from_ascii("\n\n") + _("[contains tracked changes]");
1106 support::truncateWithEllipsis(str, len);
1111 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1113 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1117 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1119 // Nested cprotect content needs \cprotect
1121 if (producesOutput() && hasCProtectContent(fragile))
1124 // Environments generally need cprotection in fragile context
1125 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1128 if (!getLayout().needsCProtect())
1131 // Environments and "no latex" types (e.g., knitr chunks)
1132 // need cprotection regardless the content
1133 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1136 // If the inset does not produce output (e.g. Note or Branch),
1137 // we can ignore the contained paragraphs
1138 if (!producesOutput())
1141 // Commands need cprotection if they contain specific chars
1142 int const nchars_escape = 9;
1143 static char_type const chars_escape[nchars_escape] = {
1144 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1146 ParagraphList const & pars = paragraphs();
1147 pit_type pend = pit_type(paragraphs().size());
1149 for (pit_type pit = 0; pit != pend; ++pit) {
1150 Paragraph const & par = pars[size_type(pit)];
1151 if (par.needsCProtection(fragile))
1153 docstring const par_str = par.asString();
1154 for (int k = 0; k < nchars_escape; k++) {
1155 if (contains(par_str, chars_escape[k]))