3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetText.h"
15 #include "insets/InsetArgument.h"
16 #include "insets/InsetLayout.h"
18 #include "buffer_funcs.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "CompletionList.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "InsetList.h"
34 #include "LaTeXFeatures.h"
38 #include "MetricsInfo.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_plaintext.h"
42 #include "output_xhtml.h"
43 #include "OutputParams.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "texstream.h"
50 #include "TextClass.h"
52 #include "TextMetrics.h"
53 #include "TocBackend.h"
54 #include "TocBuilder.h"
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
59 #include "support/convert.h"
60 #include "support/debug.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #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), intitle_context_(false),
83 frame_color_(Color_insetframe),
84 text_(this, type == DefaultLayout)
89 InsetText::InsetText(InsetText const & in)
90 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
91 intitle_context_(false), frame_color_(in.frame_color_),
97 void InsetText::setBuffer(Buffer & buf)
99 ParagraphList::iterator end = paragraphs().end();
100 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
101 it->setInsetBuffers(buf);
102 Inset::setBuffer(buf);
106 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
108 text_.setMacrocontextPosition(pos);
110 ParagraphList::const_iterator pit = paragraphs().begin();
111 ParagraphList::const_iterator pend = paragraphs().end();
112 for (; pit != pend; ++pit) {
113 InsetList::const_iterator iit = pit->insetList().begin();
114 InsetList::const_iterator end = pit->insetList().end();
115 for (; iit != end; ++iit) {
116 if (InsetText * txt = iit->inset->asInsetText()) {
117 DocIterator ppos(pos);
118 ppos.push_back(CursorSlice(*txt));
119 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
126 void InsetText::clear()
128 ParagraphList & pars = paragraphs();
129 LBUFERR(!pars.empty());
131 // This is a gross hack...
132 Layout const & old_layout = pars.begin()->layout();
135 pars.push_back(Paragraph());
136 pars.begin()->setInsetOwner(this);
137 pars.begin()->setLayout(old_layout);
141 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
143 TextMetrics const & tm = bv.textMetrics(&text_);
144 Dimension dim = tm.dim();
145 dim.wid += leftOffset(&bv) + rightOffset(&bv);
146 dim.des += bottomOffset(&bv);
147 dim.asc += topOffset(&bv);
152 void InsetText::write(ostream & os) const
159 void InsetText::read(Lexer & lex)
163 // delete the initial paragraph
164 Paragraph oldpar = *paragraphs().begin();
165 paragraphs().clear();
167 lex.setContext("InsetText::read");
168 bool res = text_.read(lex, errorList, this);
171 lex.printError("Missing \\end_inset at this point. ");
174 // ensure we have at least one paragraph.
175 if (paragraphs().empty())
176 paragraphs().push_back(oldpar);
177 // Force default font, if so requested
178 // This avoids paragraphs in buffer language that would have a
179 // foreign language after a document language change, and it ensures
180 // that all new text in ERT and similar gets the "latex" language,
181 // since new text inherits the language from the last position of the
182 // existing text. As a side effect this makes us also robust against
183 // bugs in LyX that might lead to font changes in ERT in .lyx files.
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
190 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
192 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
194 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
196 // Hand font through to contained lyxtext:
197 tm.font_.fontInfo() = mi.base.font;
198 mi.base.textwidth -= horiz_offset;
200 // This can happen when a layout has a left and right margin,
201 // and the view is made very narrow. We can't do better than
202 // to draw it partly out of view (bug 5890).
203 if (mi.base.textwidth < 1)
204 mi.base.textwidth = 1;
207 tm.metrics(mi, dim, mi.base.textwidth);
210 mi.base.textwidth += horiz_offset;
211 dim.asc += topOffset(mi.base.bv);
212 dim.des += bottomOffset(mi.base.bv);
213 dim.wid += horiz_offset;
217 void InsetText::draw(PainterInfo & pi, int x, int y) const
219 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
221 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
222 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
223 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
224 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
225 int const xframe = x + leftOffset(pi.base.bv) / 2;
226 bool change_drawn = false;
228 pi.pain.fillRectangle(xframe, yframe, w, h,
229 pi.backgroundColor(this));
232 Changer dummy = make_change(pi.background_color,
233 pi.backgroundColor(this, false));
234 // The change tracking cue must not be inherited
235 Changer dummy2 = make_change(pi.change, Change());
236 tm.draw(pi, x + leftOffset(pi.base.bv), y);
240 // Change color of the frame in tracked changes, like for tabulars.
241 // Only do so if the color is not custom. But do so even if RowPainter
242 // handles the strike-through already.
244 if (pi.change.changed()
245 // Originally, these are the colors with role Text, from role() in
246 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
247 // types, and also maybe it need not match in the future.
248 && (frameColor() == Color_foreground
249 || frameColor() == Color_cursor
250 || frameColor() == Color_preview
251 || frameColor() == Color_tabularline
252 || frameColor() == Color_previewframe)) {
253 c = pi.change.color();
257 pi.pain.rectangle(xframe, yframe, w, h, c);
260 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
261 // Do not draw the change tracking cue if already done by RowPainter and
262 // do not draw the cue for INSERTED if the information is already in the
263 // color of the frame
264 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
268 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
270 pit_type const pit = front ? 0 : paragraphs().size() - 1;
271 pos_type pos = front ? 0 : paragraphs().back().size();
273 // if visual information is not to be ignored, move to extreme right/left
274 if (entry_from != ENTRY_DIRECTION_IGNORE) {
275 Cursor temp_cur = cur;
276 temp_cur.pit() = pit;
277 temp_cur.pos() = pos;
278 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
279 pos = temp_cur.pos();
282 cur.top().setPitPos(pit, pos);
287 Inset * InsetText::editXY(Cursor & cur, int x, int y)
289 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
293 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
295 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
297 // See bug #9042, for instance.
299 // Force any new text to latex_language FIXME: This
300 // should only be necessary in constructor, but new
301 // paragraphs that are created by pressing enter at
302 // the start of an existing paragraph get the buffer
303 // language and not latex_language, so we take this
304 // brute force approach.
305 cur.current_font.setLanguage(latex_language);
306 cur.real_current_font.setLanguage(latex_language);
309 switch (cmd.action()) {
311 case LFUN_CLIPBOARD_PASTE:
312 case LFUN_SELECTION_PASTE:
313 case LFUN_PRIMARY_SELECTION_PASTE:
314 text_.dispatch(cur, cmd);
315 // If we we can only store plain text, we must reset all
317 // FIXME: Change only the pasted paragraphs
321 case LFUN_INSET_DISSOLVE: {
322 bool const main_inset = text_.isMainText();
323 bool const target_inset = cmd.argument().empty()
324 || cmd.getArg(0) == insetName(lyxCode());
326 if (!main_inset && target_inset) {
327 // Text::dissolveInset assumes that the cursor
328 // is inside the Inset.
329 if (&cur.inset() != this)
330 cur.pushBackward(*this);
331 cur.beginUndoGroup();
332 text_.dispatch(cur, cmd);
340 text_.dispatch(cur, cmd);
343 if (!cur.result().dispatched())
344 Inset::doDispatch(cur, cmd);
348 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
349 FuncStatus & status) const
351 switch (cmd.action()) {
352 case LFUN_INSET_DISSOLVE: {
353 bool const main_inset = text_.isMainText();
354 bool const target_inset = cmd.argument().empty()
355 || cmd.getArg(0) == insetName(lyxCode());
358 status.setEnabled(!main_inset);
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 // bool InsetText::isChanged() const
420 // ParagraphList::const_iterator pit = paragraphs().begin();
421 // ParagraphList::const_iterator end = paragraphs().end();
422 // for (; pit != end; ++pit) {
423 // if (pit->isChanged())
430 void InsetText::setChange(Change const & change)
432 ParagraphList::iterator pit = paragraphs().begin();
433 ParagraphList::iterator end = paragraphs().end();
434 for (; pit != end; ++pit) {
435 pit->setChange(change);
440 void InsetText::acceptChanges()
442 text_.acceptChanges();
446 void InsetText::rejectChanges()
448 text_.rejectChanges();
452 void InsetText::validate(LaTeXFeatures & features) const
454 features.useInsetLayout(getLayout());
455 for (Paragraph const & p : paragraphs())
456 p.validate(features);
460 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
462 // This implements the standard way of handling the LaTeX
463 // output of a text inset, either a command or an
464 // environment. Standard collapsible insets should not
465 // redefine this, non-standard ones may call this.
466 InsetLayout const & il = getLayout();
467 if (il.forceOwnlines())
469 bool needendgroup = false;
470 if (!il.latexname().empty()) {
471 if (il.latextype() == InsetLayout::COMMAND) {
473 // FIXME \protect should only be used for fragile
474 // commands, but we do not provide this information yet.
475 if (hasCProtectContent(runparams.moving_arg)) {
476 if (contains(runparams.active_chars, '^')) {
477 // cprotect relies on ^ being on catcode 7
478 os << "\\begingroup\\catcode`\\^=7";
482 } else if (runparams.moving_arg)
484 os << '\\' << from_utf8(il.latexname());
485 if (!il.latexargs().empty())
486 getArgs(os, runparams);
487 if (!il.latexparam().empty())
488 os << from_utf8(il.latexparam());
490 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
495 if (runparams.lastid != -1)
496 os.texrow().start(runparams.lastid,
498 os << "\\begin{" << from_utf8(il.latexname()) << "}";
499 if (!il.latexargs().empty())
500 getArgs(os, runparams);
501 if (!il.latexparam().empty())
502 os << from_utf8(il.latexparam());
506 if (!il.latexargs().empty())
507 getArgs(os, runparams);
508 if (!il.latexparam().empty())
509 os << from_utf8(il.latexparam());
512 if (!il.leftdelim().empty())
513 os << il.leftdelim();
515 OutputParams rp = runparams;
518 if (il.isNeedProtect())
519 rp.moving_arg = true;
520 if (il.isNeedMBoxProtect())
522 if (!il.passThruChars().empty())
523 rp.pass_thru_chars += il.passThruChars();
524 if (!il.newlineCmd().empty())
525 rp.newlinecmd = il.newlineCmd();
527 rp.par_end = paragraphs().size();
529 // Output the contents of the inset
530 latexParagraphs(buffer(), text_, os, rp);
531 runparams.encoding = rp.encoding;
532 // Pass the post_macros upstream
533 runparams.post_macro = rp.post_macro;
534 // These need to be passed upstream as well
535 runparams.need_maketitle = rp.need_maketitle;
536 runparams.have_maketitle = rp.have_maketitle;
538 if (!il.rightdelim().empty())
539 os << il.rightdelim();
541 if (!il.latexname().empty()) {
542 if (il.latextype() == InsetLayout::COMMAND) {
544 if (!il.postcommandargs().empty())
545 getArgs(os, runparams, true);
548 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
549 // A comment environment doesn't need a % before \n\end
550 if (il.isDisplay() || runparams.inComment)
554 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
556 os.protectSpace(true);
559 if (il.forceOwnlines())
564 int InsetText::plaintext(odocstringstream & os,
565 OutputParams const & runparams, size_t max_length) const
567 ParagraphList::const_iterator beg = paragraphs().begin();
568 ParagraphList::const_iterator end = paragraphs().end();
569 ParagraphList::const_iterator it = beg;
570 bool ref_printed = false;
572 for (; it != end; ++it) {
575 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
578 odocstringstream oss;
579 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
580 docstring const str = oss.str();
582 // FIXME: len is not computed fully correctly; in principle,
583 // we have to count the characters after the last '\n'
585 if (os.str().size() >= max_length)
594 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
596 docbook(xs, rp, WriteEverything);
600 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
602 // we will always want to output all our paragraphs when we are
604 OutputParams runparams = rp;
605 runparams.par_begin = 0;
606 runparams.par_end = text().paragraphs().size();
609 xs.startDivision(false);
610 docbookParagraphs(text_, buffer(), xs, runparams);
615 InsetLayout const & il = getLayout();
616 if (opts & WriteOuterTag && !il.docbooktag().empty() && il.docbooktag() != "NONE") {
617 docstring attrs = docstring();
618 if (!il.docbookattr().empty())
619 attrs += from_ascii(il.docbookattr());
620 if (il.docbooktag() == "link")
621 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
622 xs << xml::StartTag(il.docbooktag(), attrs);
625 // No need for labels that are generated from counters.
627 // With respect to XHTML, paragraphs are still allowed here.
628 if (!allowMultiPar())
629 runparams.docbook_make_pars = false;
631 runparams.pass_thru = true;
633 xs.startDivision(false);
634 docbookParagraphs(text_, buffer(), xs, runparams);
637 if (opts & WriteOuterTag)
638 xs << xml::EndTag(il.docbooktag());
642 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
644 return insetAsXHTML(xs, runparams, WriteEverything);
649 // There are cases where we may need to close open fonts and such
650 // and then re-open them when we are done. This would be the case, e.g.,
651 // if we were otherwise about to write:
652 // <em>word <div class='foot'>footnote text.</div> emph</em>
653 // The problem isn't so much that the footnote text will get emphasized:
654 // we can handle that with CSS. The problem is that this is invalid XHTML.
655 // One solution would be to make the footnote <span>, but the problem is
656 // completely general, and so we'd have to make absolutely everything into
657 // span. What I think will work is to check if we're about to write "div" and,
658 // if so, try to close fonts, etc.
659 // There are probably limits to how well we can do here, though, and we will
660 // have to rely upon users not putting footnotes inside noun-type insets.
661 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
662 XHTMLOptions opts) const
664 // we will always want to output all our paragraphs when we are
666 OutputParams runparams = rp;
667 runparams.par_begin = 0;
668 runparams.par_end = text().paragraphs().size();
671 xs.startDivision(false);
672 xhtmlParagraphs(text_, buffer(), xs, runparams);
677 InsetLayout const & il = getLayout();
678 if (opts & WriteOuterTag)
679 xs << xml::StartTag(il.htmltag(), il.htmlattr());
681 if ((opts & WriteLabel) && !il.counter().empty()) {
682 BufferParams const & bp = buffer().masterBuffer()->params();
683 Counters & cntrs = bp.documentClass().counters();
684 cntrs.step(il.counter(), OutputUpdate);
685 // FIXME: translate to paragraph language
686 if (!il.htmllabel().empty()) {
687 docstring const lbl =
688 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
689 // FIXME is this check necessary?
691 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
693 xs << xml::EndTag(il.htmllabeltag());
698 if (opts & WriteInnerTag)
699 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
701 // we will eventually lose information about the containing inset
702 if (!allowMultiPar() || opts == JustText)
703 runparams.html_make_pars = false;
705 runparams.pass_thru = true;
707 xs.startDivision(false);
708 xhtmlParagraphs(text_, buffer(), xs, runparams);
711 if (opts & WriteInnerTag)
712 xs << xml::EndTag(il.htmlinnertag());
714 if (opts & WriteOuterTag)
715 xs << xml::EndTag(il.htmltag());
721 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
722 bool const post) const
724 OutputParams runparams = runparams_in;
725 runparams.local_font =
726 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
728 runparams.pass_thru = true;
730 latexArgInsetsForParent(paragraphs(), os, runparams,
731 getLayout().postcommandargs(), "post:");
733 latexArgInsetsForParent(paragraphs(), os, runparams,
734 getLayout().latexargs());
738 void InsetText::cursorPos(BufferView const & bv,
739 CursorSlice const & sl, bool boundary, int & x, int & y) const
741 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
742 y = bv.textMetrics(&text_).cursorY(sl, boundary);
746 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
749 Paragraph & first = paragraphs().front();
750 for (unsigned int i = 0; i < data.length(); ++i)
751 first.insertChar(i, data[i], font, trackChanges);
755 void InsetText::setDrawFrame(bool flag)
761 ColorCode InsetText::frameColor() const
767 void InsetText::setFrameColor(ColorCode col)
773 void InsetText::appendParagraphs(ParagraphList & plist)
775 // There is little we can do here to keep track of changes.
776 // As of 2006/10/20, appendParagraphs is used exclusively by
777 // LyXTabular::setMultiColumn. In this context, the paragraph break
778 // is lost irreversibly and the appended text doesn't really change
780 ParagraphList & pl = paragraphs();
782 ParagraphList::iterator pit = plist.begin();
783 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
785 mergeParagraph(buffer().params(), pl,
786 distance(pl.begin(), ins) - 1);
788 ParagraphList::iterator const pend = plist.end();
789 for (; pit != pend; ++pit)
794 void InsetText::addPreview(DocIterator const & text_inset_pos,
795 PreviewLoader & loader) const
797 ParagraphList::const_iterator pit = paragraphs().begin();
798 ParagraphList::const_iterator pend = paragraphs().end();
801 DocIterator inset_pos = text_inset_pos;
802 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
804 for (; pit != pend; ++pit, ++pidx) {
805 InsetList::const_iterator it = pit->insetList().begin();
806 InsetList::const_iterator end = pit->insetList().end();
807 inset_pos.pit() = pidx;
808 for (; it != end; ++it) {
809 inset_pos.pos() = it->pos;
810 it->inset->addPreview(inset_pos, loader);
816 ParagraphList const & InsetText::paragraphs() const
818 return text_.paragraphs();
822 ParagraphList & InsetText::paragraphs()
824 return text_.paragraphs();
828 bool InsetText::hasCProtectContent(bool fragile) const
830 fragile |= getLayout().isNeedProtect();
831 ParagraphList const & pars = paragraphs();
832 pit_type pend = pit_type(paragraphs().size());
833 for (pit_type pit = 0; pit != pend; ++pit) {
834 Paragraph const & par = pars[size_type(pit)];
835 if (par.needsCProtection(fragile))
842 bool InsetText::insetAllowed(InsetCode code) const
845 // Arguments and (plain) quotes are also allowed in PassThru insets
850 return !isPassThru();
855 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
857 ParIterator it2 = it;
859 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
860 if (producesOutput()) {
861 InsetLayout const & il = getLayout();
862 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
863 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
865 // LYXERR0("Entering " << name());
866 cnt.clearLastLayout();
867 // FIXME cnt.saveLastCounter()?
869 buffer().updateBuffer(it2, utype, deleted);
871 // LYXERR0("Exiting " << name());
872 cnt.restoreLastLayout();
873 // FIXME cnt.restoreLastCounter()?
875 // Record in this inset is embedded in a title layout
876 // This is needed to decide when \maketitle is output.
877 intitle_context_ = it.paragraph().layout().intitle;
878 // Also check embedding layouts
879 size_t const n = it.depth();
880 for (size_t i = 0; i < n; ++i) {
881 if (it[i].paragraph().layout().intitle) {
882 intitle_context_ = true;
887 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
888 // Note that we do not need to call:
889 // tclass.counters().clearLastLayout()
890 // since we are saving and restoring the existing counters, etc.
891 Counters savecnt = tclass.counters();
892 tclass.counters().reset();
893 // we need float information even in note insets (#9760)
894 tclass.counters().current_float(savecnt.current_float());
895 tclass.counters().isSubfloat(savecnt.isSubfloat());
896 buffer().updateBuffer(it2, utype, deleted);
897 tclass.counters() = move(savecnt);
902 void InsetText::toString(odocstream & os) const
904 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
908 void InsetText::forOutliner(docstring & os, size_t const maxlen,
909 bool const shorten) const
911 if (!getLayout().isInToc())
913 text().forOutliner(os, maxlen, shorten);
917 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
918 UpdateType utype, TocBackend & backend) const
920 DocIterator dit = cdit;
921 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
922 iterateForToc(dit, output_active, utype, backend);
926 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
927 UpdateType utype, TocBackend & backend) const
929 DocIterator dit = cdit;
930 // This also ensures that any document has a table of contents
931 shared_ptr<Toc> toc = backend.toc("tableofcontents");
933 BufferParams const & bufparams = buffer_->params();
934 int const min_toclevel = bufparams.documentClass().min_toclevel();
935 // we really should have done this before we got here, but it
936 // can't hurt too much to do it again
937 bool const doing_output = output_active && producesOutput();
939 // For each paragraph,
940 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
941 // paragraphs as needed.
942 // * Traverse its insets and let them add their toc items
943 // * Compute the main table of contents (this is hardcoded)
944 // * Add the list of changes
945 ParagraphList const & pars = paragraphs();
946 pit_type pend = paragraphs().size();
947 // Record pairs {start,end} of where a toc item was opened for a paragraph
948 // and where it must be closed
949 stack<pair<pit_type, pit_type>> addtotoc_stack;
951 for (pit_type pit = 0; pit != pend; ++pit) {
952 Paragraph const & par = pars[pit];
956 // Custom AddToToc in paragraph layouts (i.e. theorems)
957 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
959 openAddToTocForParagraph(pit, dit, output_active, backend);
960 addtotoc_stack.push({pit, end});
963 // If we find an InsetArgument that is supposed to provide the TOC caption,
964 // we'll save it for use later.
965 InsetArgument const * arginset = nullptr;
966 for (auto const & table : par.insetList()) {
967 dit.pos() = table.pos;
968 table.inset->addToToc(dit, doing_output, utype, backend);
969 if (InsetArgument const * x = table.inset->asInsetArgument())
970 if (x->isTocCaption())
974 // End custom AddToToc in paragraph layouts
975 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
976 // execute the closing function
977 closeAddToTocForParagraph(addtotoc_stack.top().first,
978 addtotoc_stack.top().second, backend);
979 addtotoc_stack.pop();
982 // now the toc entry for the paragraph in the main table of contents
983 int const toclevel = text().getTocLevel(pit);
984 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
985 // insert this into the table of contents
987 int const length = (doing_output && utype == OutputUpdate) ?
988 INT_MAX : TOC_ENTRY_LENGTH;
990 tocstring = par.labelString();
991 if (!tocstring.empty())
993 arginset->text().forOutliner(tocstring, length);
995 par.forOutliner(tocstring, length);
997 toc->push_back(TocItem(dit, toclevel - min_toclevel,
998 tocstring, doing_output));
1001 // And now the list of changes.
1002 par.addChangesToToc(dit, buffer(), doing_output, backend);
1007 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1008 DocIterator const & dit,
1010 TocBackend & backend) const
1012 Paragraph const & par = paragraphs()[pit];
1013 TocBuilder & b = backend.builder(par.layout().tocType());
1014 docstring const & label = par.labelString();
1015 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1016 return text().lastInSequence(pit);
1020 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1021 TocBackend & backend) const
1023 Paragraph const & par = paragraphs()[start];
1024 TocBuilder & b = backend.builder(par.layout().tocType());
1025 if (par.layout().isTocCaption()) {
1027 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1028 b.argumentItem(str);
1034 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1036 if (buffer().isClean())
1037 return Inset::notifyCursorLeaves(old, cur);
1039 // find text inset in old cursor
1040 Cursor insetCur = old;
1041 int scriptSlice = insetCur.find(this);
1042 // we can try to continue here. returning true means
1043 // the cursor is "now" invalid. which it was.
1044 LASSERT(scriptSlice != -1, return true);
1045 insetCur.cutOff(scriptSlice);
1046 LASSERT(&insetCur.inset() == this, return true);
1048 // update the old paragraph's words
1049 insetCur.paragraph().updateWords();
1051 return Inset::notifyCursorLeaves(old, cur);
1055 bool InsetText::completionSupported(Cursor const & cur) const
1057 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1058 return text_.completionSupported(cur);
1062 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1064 return completionSupported(cur);
1068 bool InsetText::automaticInlineCompletion() const
1070 return lyxrc.completion_inline_text;
1074 bool InsetText::automaticPopupCompletion() const
1076 return lyxrc.completion_popup_text;
1080 bool InsetText::showCompletionCursor() const
1082 return lyxrc.completion_cursor_text;
1086 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1088 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1092 docstring InsetText::completionPrefix(Cursor const & cur) const
1094 if (!completionSupported(cur))
1096 return text_.completionPrefix(cur);
1100 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1103 if (!completionSupported(cur))
1106 return text_.insertCompletion(cur, s, finished);
1110 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1111 Dimension & dim) const
1113 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1114 tm.completionPosAndDim(cur, x, y, dim);
1118 string InsetText::contextMenu(BufferView const &, int, int) const
1120 string context_menu = contextMenuName();
1121 if (context_menu != InsetText::contextMenuName())
1122 context_menu += ";" + InsetText::contextMenuName();
1123 return context_menu;
1127 string InsetText::contextMenuName() const
1129 return "context-edit";
1133 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1135 OutputParams rp(&buffer().params().encoding());
1136 rp.for_tooltip = true;
1137 odocstringstream oss;
1140 ParagraphList::const_iterator beg = paragraphs().begin();
1141 ParagraphList::const_iterator end = paragraphs().end();
1142 ParagraphList::const_iterator it = beg;
1143 bool ref_printed = false;
1145 for (; it != end; ++it) {
1148 if ((*it).isRTL(buffer().params()))
1149 oss << "<div dir=\"rtl\">";
1150 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1151 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1154 docstring str = oss.str();
1156 str += from_ascii("\n\n") + _("[contains tracked changes]");
1157 support::truncateWithEllipsis(str, len);
1162 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1164 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1168 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1170 // Nested cprotect content needs \cprotect
1172 if (producesOutput() && hasCProtectContent(fragile))
1175 // Environments generally need cprotection in fragile context
1176 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1179 if (!getLayout().needsCProtect())
1182 // Environments and "no latex" types (e.g., knitr chunks)
1183 // need cprotection regardless the content
1184 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1187 // If the inset does not produce output (e.g. Note or Branch),
1188 // we can ignore the contained paragraphs
1189 if (!producesOutput())
1192 // Commands need cprotection if they contain specific chars
1193 int const nchars_escape = 9;
1194 static char_type const chars_escape[nchars_escape] = {
1195 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1197 ParagraphList const & pars = paragraphs();
1198 pit_type pend = pit_type(paragraphs().size());
1200 for (pit_type pit = 0; pit != pend; ++pit) {
1201 Paragraph const & par = pars[size_type(pit)];
1202 if (par.needsCProtection(fragile))
1204 docstring const par_str = par.asString();
1205 for (int k = 0; k < nchars_escape; k++) {
1206 if (contains(par_str, chars_escape[k]))