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), text_(this, in.text_)
91 drawFrame_ = in.drawFrame_;
92 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());
321 // cur.inset() is the tabular when this is a single cell (bug #9954)
322 bool const one_cell = cur.inset().nargs() == 1;
324 if (!main_inset && target_inset && one_cell) {
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());
354 // cur.inset() is the tabular when this is a single cell (bug #9954)
355 bool const one_cell = cur.inset().nargs() == 1;
358 status.setEnabled(!main_inset && one_cell);
362 case LFUN_ARGUMENT_INSERT: {
363 string const arg = cmd.getArg(0);
365 status.setEnabled(false);
368 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
369 return text_.getStatus(cur, cmd, status);
371 Layout::LaTeXArgMap args = getLayout().args();
372 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
373 if (lait != args.end()) {
374 status.setEnabled(true);
375 for (Paragraph const & par : paragraphs())
376 for (auto const & table : par.insetList())
377 if (InsetArgument const * ins = table.inset->asInsetArgument())
378 if (ins->name() == arg) {
379 // we have this already
380 status.setEnabled(false);
384 status.setEnabled(false);
389 // Dispatch only to text_ if the cursor is inside
390 // the text_. It is not for context menus (bug 5797).
392 if (cur.text() == &text_)
393 ret = text_.getStatus(cur, cmd, status);
396 ret = Inset::getStatus(cur, cmd, status);
402 void InsetText::fixParagraphsFont()
404 Font font(inherit_font, buffer().params().language);
405 font.setLanguage(latex_language);
406 ParagraphList::iterator par = paragraphs().begin();
407 ParagraphList::iterator const end = paragraphs().end();
409 if (par->isPassThru())
410 par->resetFonts(font);
411 if (!par->allowParagraphCustomization())
412 par->params().clear();
418 void InsetText::setChange(Change const & change)
420 ParagraphList::iterator pit = paragraphs().begin();
421 ParagraphList::iterator end = paragraphs().end();
422 for (; pit != end; ++pit) {
423 pit->setChange(change);
428 void InsetText::acceptChanges()
430 text_.acceptChanges();
434 void InsetText::rejectChanges()
436 text_.rejectChanges();
440 void InsetText::validate(LaTeXFeatures & features) const
442 features.useInsetLayout(getLayout());
443 for (Paragraph const & p : paragraphs())
444 p.validate(features);
448 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
450 // This implements the standard way of handling the LaTeX
451 // output of a text inset, either a command or an
452 // environment. Standard collapsible insets should not
453 // redefine this, non-standard ones may call this.
454 InsetLayout const & il = getLayout();
455 if (il.forceOwnlines())
457 bool needendgroup = false;
458 if (!il.latexname().empty()) {
459 if (il.latextype() == InsetLayout::COMMAND) {
461 // FIXME \protect should only be used for fragile
462 // commands, but we do not provide this information yet.
463 if (hasCProtectContent(runparams.moving_arg)) {
464 if (contains(runparams.active_chars, '^')) {
465 // cprotect relies on ^ being ignored
466 os << "\\begingroup\\catcode`\\^=9";
470 } else if (runparams.moving_arg)
472 os << '\\' << from_utf8(il.latexname());
473 if (!il.latexargs().empty())
474 getArgs(os, runparams);
475 if (!il.latexparam().empty())
476 os << from_utf8(il.latexparam());
478 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
483 if (runparams.lastid != -1)
484 os.texrow().start(runparams.lastid,
486 os << "\\begin{" << from_utf8(il.latexname()) << "}";
487 if (!il.latexargs().empty())
488 getArgs(os, runparams);
489 if (!il.latexparam().empty())
490 os << from_utf8(il.latexparam());
494 if (!il.latexargs().empty())
495 getArgs(os, runparams);
496 if (!il.latexparam().empty())
497 os << from_utf8(il.latexparam());
500 if (!il.leftdelim().empty())
501 os << il.leftdelim();
503 OutputParams rp = runparams;
506 if (il.isNeedProtect())
507 rp.moving_arg = true;
508 if (il.isNeedMBoxProtect())
510 if (!il.passThruChars().empty())
511 rp.pass_thru_chars += il.passThruChars();
512 if (!il.newlineCmd().empty())
513 rp.newlinecmd = il.newlineCmd();
515 rp.par_end = paragraphs().size();
517 // Output the contents of the inset
518 latexParagraphs(buffer(), text_, os, rp);
519 runparams.encoding = rp.encoding;
520 // Pass the post_macros upstream
521 runparams.post_macro = rp.post_macro;
523 if (!il.rightdelim().empty())
524 os << il.rightdelim();
526 if (!il.latexname().empty()) {
527 if (il.latextype() == InsetLayout::COMMAND) {
529 if (!il.postcommandargs().empty())
530 getArgs(os, runparams, true);
533 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
534 // A comment environment doesn't need a % before \n\end
535 if (il.isDisplay() || runparams.inComment)
539 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
541 os.protectSpace(true);
544 if (il.forceOwnlines())
549 int InsetText::plaintext(odocstringstream & os,
550 OutputParams const & runparams, size_t max_length) const
552 ParagraphList::const_iterator beg = paragraphs().begin();
553 ParagraphList::const_iterator end = paragraphs().end();
554 ParagraphList::const_iterator it = beg;
555 bool ref_printed = false;
557 for (; it != end; ++it) {
560 if (runparams.linelen > 0)
563 odocstringstream oss;
564 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
565 docstring const str = oss.str();
567 // FIXME: len is not computed fully correctly; in principle,
568 // we have to count the characters after the last '\n'
570 if (os.str().size() >= max_length)
578 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
580 ParagraphList::const_iterator const beg = paragraphs().begin();
583 sgml::openTag(os, getLayout().latexname(),
584 beg->getID(buffer(), runparams) + getLayout().latexparam());
586 docbookParagraphs(text_, buffer(), os, runparams);
589 sgml::closeTag(os, getLayout().latexname());
595 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
597 return insetAsXHTML(xs, runparams, WriteEverything);
602 // There are cases where we may need to close open fonts and such
603 // and then re-open them when we are done. This would be the case, e.g.,
604 // if we were otherwise about to write:
605 // <em>word <div class='foot'>footnote text.</div> emph</em>
606 // The problem isn't so much that the footnote text will get emphasized:
607 // we can handle that with CSS. The problem is that this is invalid XHTML.
608 // One solution would be to make the footnote <span>, but the problem is
609 // completely general, and so we'd have to make absolutely everything into
610 // span. What I think will work is to check if we're about to write "div" and,
611 // if so, try to close fonts, etc.
612 // There are probably limits to how well we can do here, though, and we will
613 // have to rely upon users not putting footnotes inside noun-type insets.
614 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
615 XHTMLOptions opts) const
617 // we will always want to output all our paragraphs when we are
619 OutputParams runparams = rp;
620 runparams.par_begin = 0;
621 runparams.par_end = text().paragraphs().size();
624 xs.startDivision(false);
625 xhtmlParagraphs(text_, buffer(), xs, runparams);
630 InsetLayout const & il = getLayout();
631 if (opts & WriteOuterTag)
632 xs << html::StartTag(il.htmltag(), il.htmlattr());
634 if ((opts & WriteLabel) && !il.counter().empty()) {
635 BufferParams const & bp = buffer().masterBuffer()->params();
636 Counters & cntrs = bp.documentClass().counters();
637 cntrs.step(il.counter(), OutputUpdate);
638 // FIXME: translate to paragraph language
639 if (!il.htmllabel().empty()) {
640 docstring const lbl =
641 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
642 // FIXME is this check necessary?
644 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
646 xs << html::EndTag(il.htmllabeltag());
651 if (opts & WriteInnerTag)
652 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
654 // we will eventually lose information about the containing inset
655 if (!allowMultiPar() || opts == JustText)
656 runparams.html_make_pars = false;
658 runparams.pass_thru = true;
660 xs.startDivision(false);
661 xhtmlParagraphs(text_, buffer(), xs, runparams);
664 if (opts & WriteInnerTag)
665 xs << html::EndTag(il.htmlinnertag());
667 if (opts & WriteOuterTag)
668 xs << html::EndTag(il.htmltag());
674 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
675 bool const post) const
677 OutputParams runparams = runparams_in;
678 runparams.local_font =
679 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
681 runparams.pass_thru = true;
683 latexArgInsetsForParent(paragraphs(), os, runparams,
684 getLayout().postcommandargs(), "post:");
686 latexArgInsetsForParent(paragraphs(), os, runparams,
687 getLayout().latexargs());
691 void InsetText::cursorPos(BufferView const & bv,
692 CursorSlice const & sl, bool boundary, int & x, int & y) const
694 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
695 y = bv.textMetrics(&text_).cursorY(sl, boundary);
699 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
702 Paragraph & first = paragraphs().front();
703 for (unsigned int i = 0; i < data.length(); ++i)
704 first.insertChar(i, data[i], font, trackChanges);
708 void InsetText::setDrawFrame(bool flag)
714 ColorCode InsetText::frameColor() const
720 void InsetText::setFrameColor(ColorCode col)
726 void InsetText::appendParagraphs(ParagraphList & plist)
728 // There is little we can do here to keep track of changes.
729 // As of 2006/10/20, appendParagraphs is used exclusively by
730 // LyXTabular::setMultiColumn. In this context, the paragraph break
731 // is lost irreversibly and the appended text doesn't really change
733 ParagraphList & pl = paragraphs();
735 ParagraphList::iterator pit = plist.begin();
736 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
738 mergeParagraph(buffer().params(), pl,
739 distance(pl.begin(), ins) - 1);
741 for_each(pit, plist.end(),
742 bind(&ParagraphList::push_back, ref(pl), _1));
746 void InsetText::addPreview(DocIterator const & text_inset_pos,
747 PreviewLoader & loader) const
749 ParagraphList::const_iterator pit = paragraphs().begin();
750 ParagraphList::const_iterator pend = paragraphs().end();
753 DocIterator inset_pos = text_inset_pos;
754 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
756 for (; pit != pend; ++pit, ++pidx) {
757 InsetList::const_iterator it = pit->insetList().begin();
758 InsetList::const_iterator end = pit->insetList().end();
759 inset_pos.pit() = pidx;
760 for (; it != end; ++it) {
761 inset_pos.pos() = it->pos;
762 it->inset->addPreview(inset_pos, loader);
768 ParagraphList const & InsetText::paragraphs() const
770 return text_.paragraphs();
774 ParagraphList & InsetText::paragraphs()
776 return text_.paragraphs();
780 bool InsetText::hasCProtectContent(bool fragile) const
782 fragile |= getLayout().isNeedProtect();
783 ParagraphList const & pars = paragraphs();
784 pit_type pend = pit_type(paragraphs().size());
785 for (pit_type pit = 0; pit != pend; ++pit) {
786 Paragraph const & par = pars[size_type(pit)];
787 if (par.needsCProtection(fragile))
794 bool InsetText::insetAllowed(InsetCode code) const
797 // Arguments and (plain) quotes are also allowed in PassThru insets
802 return !isPassThru();
807 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
809 ParIterator it2 = it;
811 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
812 if (producesOutput()) {
813 InsetLayout const & il = getLayout();
814 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
815 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
817 // LYXERR0("Entering " << name());
818 cnt.clearLastLayout();
819 // FIXME cnt.saveLastCounter()?
821 buffer().updateBuffer(it2, utype);
823 // LYXERR0("Exiting " << name());
824 cnt.restoreLastLayout();
825 // FIXME cnt.restoreLastCounter()?
828 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
829 // Note that we do not need to call:
830 // tclass.counters().clearLastLayout()
831 // since we are saving and restoring the existing counters, etc.
832 Counters savecnt = tclass.counters();
833 tclass.counters().reset();
834 // we need float information even in note insets (#9760)
835 tclass.counters().current_float(savecnt.current_float());
836 tclass.counters().isSubfloat(savecnt.isSubfloat());
837 buffer().updateBuffer(it2, utype);
838 tclass.counters() = move(savecnt);
843 void InsetText::toString(odocstream & os) const
845 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
849 void InsetText::forOutliner(docstring & os, size_t const maxlen,
850 bool const shorten) const
852 if (!getLayout().isInToc())
854 text().forOutliner(os, maxlen, shorten);
858 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
859 UpdateType utype, TocBackend & backend) const
861 DocIterator dit = cdit;
862 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
863 iterateForToc(dit, output_active, utype, backend);
867 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
868 UpdateType utype, TocBackend & backend) const
870 DocIterator dit = cdit;
871 // This also ensures that any document has a table of contents
872 shared_ptr<Toc> toc = backend.toc("tableofcontents");
874 BufferParams const & bufparams = buffer_->params();
875 int const min_toclevel = bufparams.documentClass().min_toclevel();
876 // we really should have done this before we got here, but it
877 // can't hurt too much to do it again
878 bool const doing_output = output_active && producesOutput();
880 // For each paragraph,
881 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
882 // paragraphs as needed.
883 // * Traverse its insets and let them add their toc items
884 // * Compute the main table of contents (this is hardcoded)
885 // * Add the list of changes
886 ParagraphList const & pars = paragraphs();
887 pit_type pend = paragraphs().size();
888 // Record pairs {start,end} of where a toc item was opened for a paragraph
889 // and where it must be closed
890 stack<pair<pit_type, pit_type>> addtotoc_stack;
892 for (pit_type pit = 0; pit != pend; ++pit) {
893 Paragraph const & par = pars[pit];
897 // Custom AddToToc in paragraph layouts (i.e. theorems)
898 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
900 openAddToTocForParagraph(pit, dit, output_active, backend);
901 addtotoc_stack.push({pit, end});
904 // If we find an InsetArgument that is supposed to provide the TOC caption,
905 // we'll save it for use later.
906 InsetArgument const * arginset = nullptr;
907 for (auto const & table : par.insetList()) {
908 dit.pos() = table.pos;
909 table.inset->addToToc(dit, doing_output, utype, backend);
910 if (InsetArgument const * x = table.inset->asInsetArgument())
911 if (x->isTocCaption())
915 // End custom AddToToc in paragraph layouts
916 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
917 // execute the closing function
918 closeAddToTocForParagraph(addtotoc_stack.top().first,
919 addtotoc_stack.top().second, backend);
920 addtotoc_stack.pop();
923 // now the toc entry for the paragraph in the main table of contents
924 int const toclevel = text().getTocLevel(pit);
925 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
926 // insert this into the table of contents
928 int const length = (doing_output && utype == OutputUpdate) ?
929 INT_MAX : TOC_ENTRY_LENGTH;
931 tocstring = par.labelString();
932 if (!tocstring.empty())
934 arginset->text().forOutliner(tocstring, length);
936 par.forOutliner(tocstring, length);
938 toc->push_back(TocItem(dit, toclevel - min_toclevel,
939 tocstring, doing_output));
942 // And now the list of changes.
943 par.addChangesToToc(dit, buffer(), doing_output, backend);
948 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
949 DocIterator const & dit,
951 TocBackend & backend) const
953 Paragraph const & par = paragraphs()[pit];
954 TocBuilder & b = backend.builder(par.layout().tocType());
955 docstring const label = par.labelString();
956 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
957 return text().lastInSequence(pit);
961 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
962 TocBackend & backend) const
964 Paragraph const & par = paragraphs()[start];
965 TocBuilder & b = backend.builder(par.layout().tocType());
966 if (par.layout().isTocCaption()) {
968 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
975 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
977 if (buffer().isClean())
978 return Inset::notifyCursorLeaves(old, cur);
980 // find text inset in old cursor
981 Cursor insetCur = old;
982 int scriptSlice = insetCur.find(this);
983 // we can try to continue here. returning true means
984 // the cursor is "now" invalid. which it was.
985 LASSERT(scriptSlice != -1, return true);
986 insetCur.cutOff(scriptSlice);
987 LASSERT(&insetCur.inset() == this, return true);
989 // update the old paragraph's words
990 insetCur.paragraph().updateWords();
992 return Inset::notifyCursorLeaves(old, cur);
996 bool InsetText::completionSupported(Cursor const & cur) const
998 //LASSERT(&cur.bv().cursor().inset() == this, return false);
999 return text_.completionSupported(cur);
1003 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1005 return completionSupported(cur);
1009 bool InsetText::automaticInlineCompletion() const
1011 return lyxrc.completion_inline_text;
1015 bool InsetText::automaticPopupCompletion() const
1017 return lyxrc.completion_popup_text;
1021 bool InsetText::showCompletionCursor() const
1023 return lyxrc.completion_cursor_text;
1027 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1029 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1033 docstring InsetText::completionPrefix(Cursor const & cur) const
1035 if (!completionSupported(cur))
1037 return text_.completionPrefix(cur);
1041 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1044 if (!completionSupported(cur))
1047 return text_.insertCompletion(cur, s, finished);
1051 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1052 Dimension & dim) const
1054 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1055 tm.completionPosAndDim(cur, x, y, dim);
1059 string InsetText::contextMenu(BufferView const &, int, int) const
1061 string context_menu = contextMenuName();
1062 if (context_menu != InsetText::contextMenuName())
1063 context_menu += ";" + InsetText::contextMenuName();
1064 return context_menu;
1068 string InsetText::contextMenuName() const
1070 return "context-edit";
1074 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1076 OutputParams rp(&buffer().params().encoding());
1077 rp.for_tooltip = true;
1078 odocstringstream oss;
1081 ParagraphList::const_iterator beg = paragraphs().begin();
1082 ParagraphList::const_iterator end = paragraphs().end();
1083 ParagraphList::const_iterator it = beg;
1084 bool ref_printed = false;
1086 for (; it != end; ++it) {
1089 if ((*it).isRTL(buffer().params()))
1090 oss << "<div dir=\"rtl\">";
1091 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1092 if ((*it).isRTL(buffer().params()))
1094 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1097 docstring str = oss.str();
1098 support::truncateWithEllipsis(str, len);
1103 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1105 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1109 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1111 // Nested cprotect content needs \cprotect
1113 if (producesOutput() && hasCProtectContent(fragile))
1116 // Environments generally need cprotection in fragile context
1117 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1120 if (!getLayout().needsCProtect())
1123 // Environments and "no latex" types (e.g., knitr chunks)
1124 // need cprotection regardless the content
1125 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1128 // If the inset does not produce output (e.g. Note or Branch),
1129 // we can ignore the contained paragraphs
1130 if (!producesOutput())
1133 // Commands need cprotection if they contain specific chars
1134 int const nchars_escape = 9;
1135 static char_type const chars_escape[nchars_escape] = {
1136 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1138 ParagraphList const & pars = paragraphs();
1139 pit_type pend = pit_type(paragraphs().size());
1141 for (pit_type pit = 0; pit != pend; ++pit) {
1142 Paragraph const & par = pars[size_type(pit)];
1143 if (par.needsCProtection(fragile))
1145 docstring const pars = par.asString();
1146 for (int k = 0; k < nchars_escape; k++) {
1147 if (contains(pars, chars_escape[k]))