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/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"
70 using namespace lyx::support;
75 using graphics::PreviewLoader;
78 /////////////////////////////////////////////////////////////////////
80 InsetText::InsetText(Buffer * buf, UsePlain type)
81 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
82 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 intitle_context_(false), 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 += leftOffset(&bv) + rightOffset(&bv);
145 dim.des += bottomOffset(&bv);
146 dim.asc += topOffset(&bv);
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 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
195 // Hand font through to contained lyxtext:
196 tm.font_.fontInfo() = mi.base.font;
197 mi.base.textwidth -= horiz_offset;
199 // This can happen when a layout has a left and right margin,
200 // and the view is made very narrow. We can't do better than
201 // to draw it partly out of view (bug 5890).
202 if (mi.base.textwidth < 1)
203 mi.base.textwidth = 1;
206 tm.metrics(mi, dim, mi.base.textwidth);
209 mi.base.textwidth += horiz_offset;
210 dim.asc += topOffset(mi.base.bv);
211 dim.des += bottomOffset(mi.base.bv);
212 dim.wid += horiz_offset;
216 void InsetText::draw(PainterInfo & pi, int x, int y) const
218 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
220 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
221 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
222 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
223 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
224 int const xframe = x + leftOffset(pi.base.bv) / 2;
225 bool change_drawn = false;
227 pi.pain.fillRectangle(xframe, yframe, w, h,
228 pi.backgroundColor(this));
231 Changer dummy = make_change(pi.background_color,
232 pi.backgroundColor(this, false));
233 // The change tracking cue must not be inherited
234 Changer dummy2 = make_change(pi.change, Change());
235 tm.draw(pi, x + leftOffset(pi.base.bv), y);
239 // Change color of the frame in tracked changes, like for tabulars.
240 // Only do so if the color is not custom. But do so even if RowPainter
241 // handles the strike-through already.
243 if (pi.change.changed()
244 // Originally, these are the colors with role Text, from role() in
245 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
246 // types, and also maybe it need not match in the future.
247 && (frameColor() == Color_foreground
248 || frameColor() == Color_cursor
249 || frameColor() == Color_preview
250 || frameColor() == Color_tabularline
251 || frameColor() == Color_previewframe)) {
252 c = pi.change.color();
256 pi.pain.rectangle(xframe, yframe, w, h, c);
259 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
260 // Do not draw the change tracking cue if already done by RowPainter and
261 // do not draw the cue for INSERTED if the information is already in the
262 // color of the frame
263 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
267 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
269 pit_type const pit = front ? 0 : paragraphs().size() - 1;
270 pos_type pos = front ? 0 : paragraphs().back().size();
272 // if visual information is not to be ignored, move to extreme right/left
273 if (entry_from != ENTRY_DIRECTION_IGNORE) {
274 Cursor temp_cur = cur;
275 temp_cur.pit() = pit;
276 temp_cur.pos() = pos;
277 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
278 pos = temp_cur.pos();
281 cur.top().setPitPos(pit, pos);
286 Inset * InsetText::editXY(Cursor & cur, int x, int y)
288 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
292 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
294 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
296 // See bug #9042, for instance.
298 // Force any new text to latex_language FIXME: This
299 // should only be necessary in constructor, but new
300 // paragraphs that are created by pressing enter at
301 // the start of an existing paragraph get the buffer
302 // language and not latex_language, so we take this
303 // brute force approach.
304 cur.current_font.setLanguage(latex_language);
305 cur.real_current_font.setLanguage(latex_language);
308 switch (cmd.action()) {
310 case LFUN_CLIPBOARD_PASTE:
311 case LFUN_SELECTION_PASTE:
312 case LFUN_PRIMARY_SELECTION_PASTE:
313 text_.dispatch(cur, cmd);
314 // If we we can only store plain text, we must reset all
316 // FIXME: Change only the pasted paragraphs
320 case LFUN_INSET_DISSOLVE: {
321 bool const main_inset = text_.isMainText();
322 bool const target_inset = cmd.argument().empty()
323 || cmd.getArg(0) == insetName(lyxCode());
325 if (!main_inset && target_inset) {
326 // Text::dissolveInset assumes that the cursor
327 // is inside the Inset.
328 if (&cur.inset() != this)
329 cur.pushBackward(*this);
330 cur.beginUndoGroup();
331 text_.dispatch(cur, cmd);
339 text_.dispatch(cur, cmd);
342 if (!cur.result().dispatched())
343 Inset::doDispatch(cur, cmd);
347 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
348 FuncStatus & status) const
350 switch (cmd.action()) {
351 case LFUN_INSET_DISSOLVE: {
352 bool const main_inset = text_.isMainText();
353 bool const target_inset = cmd.argument().empty()
354 || cmd.getArg(0) == insetName(lyxCode());
357 status.setEnabled(!main_inset);
361 case LFUN_ARGUMENT_INSERT: {
362 string const arg = cmd.getArg(0);
364 status.setEnabled(false);
367 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
368 return text_.getStatus(cur, cmd, status);
370 Layout::LaTeXArgMap args = getLayout().args();
371 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
372 if (lait != args.end()) {
373 status.setEnabled(true);
374 for (Paragraph const & par : paragraphs())
375 for (auto const & table : par.insetList())
376 if (InsetArgument const * ins = table.inset->asInsetArgument())
377 if (ins->name() == arg) {
378 // we have this already
379 status.setEnabled(false);
383 status.setEnabled(false);
388 // Dispatch only to text_ if the cursor is inside
389 // the text_. It is not for context menus (bug 5797).
391 if (cur.text() == &text_)
392 ret = text_.getStatus(cur, cmd, status);
395 ret = Inset::getStatus(cur, cmd, status);
401 void InsetText::fixParagraphsFont()
403 Font font(inherit_font, buffer().params().language);
404 font.setLanguage(latex_language);
405 ParagraphList::iterator par = paragraphs().begin();
406 ParagraphList::iterator const end = paragraphs().end();
408 if (par->isPassThru())
409 par->resetFonts(font);
410 if (!par->allowParagraphCustomization())
411 par->params().clear();
417 // bool InsetText::isChanged() const
419 // ParagraphList::const_iterator pit = paragraphs().begin();
420 // ParagraphList::const_iterator end = paragraphs().end();
421 // for (; pit != end; ++pit) {
422 // if (pit->isChanged())
429 void InsetText::setChange(Change const & change)
431 ParagraphList::iterator pit = paragraphs().begin();
432 ParagraphList::iterator end = paragraphs().end();
433 for (; pit != end; ++pit) {
434 pit->setChange(change);
439 void InsetText::acceptChanges()
441 text_.acceptChanges();
445 void InsetText::rejectChanges()
447 text_.rejectChanges();
451 void InsetText::validate(LaTeXFeatures & features) const
453 features.useInsetLayout(getLayout());
454 for (Paragraph const & p : paragraphs())
455 p.validate(features);
459 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
461 // This implements the standard way of handling the LaTeX
462 // output of a text inset, either a command or an
463 // environment. Standard collapsible insets should not
464 // redefine this, non-standard ones may call this.
465 InsetLayout const & il = getLayout();
466 if (il.forceOwnlines())
468 bool needendgroup = false;
469 if (!il.latexname().empty()) {
470 if (il.latextype() == InsetLayout::COMMAND) {
472 // FIXME \protect should only be used for fragile
473 // commands, but we do not provide this information yet.
474 if (hasCProtectContent(runparams.moving_arg)) {
475 if (contains(runparams.active_chars, '^')) {
476 // cprotect relies on ^ being on catcode 7
477 os << "\\begingroup\\catcode`\\^=7";
481 } else if (runparams.moving_arg)
483 os << '\\' << from_utf8(il.latexname());
484 if (!il.latexargs().empty())
485 getArgs(os, runparams);
486 if (!il.latexparam().empty())
487 os << from_utf8(il.latexparam());
489 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
494 if (runparams.lastid != -1)
495 os.texrow().start(runparams.lastid,
497 os << "\\begin{" << from_utf8(il.latexname()) << "}";
498 if (!il.latexargs().empty())
499 getArgs(os, runparams);
500 if (!il.latexparam().empty())
501 os << from_utf8(il.latexparam());
505 if (!il.latexargs().empty())
506 getArgs(os, runparams);
507 if (!il.latexparam().empty())
508 os << from_utf8(il.latexparam());
511 if (!il.leftdelim().empty())
512 os << il.leftdelim();
514 OutputParams rp = runparams;
517 if (il.isNeedProtect())
518 rp.moving_arg = true;
519 if (il.isNeedMBoxProtect())
521 if (!il.passThruChars().empty())
522 rp.pass_thru_chars += il.passThruChars();
523 if (!il.newlineCmd().empty())
524 rp.newlinecmd = il.newlineCmd();
526 rp.par_end = paragraphs().size();
528 // Output the contents of the inset
529 latexParagraphs(buffer(), text_, os, rp);
530 runparams.encoding = rp.encoding;
531 // Pass the post_macros upstream
532 runparams.post_macro = rp.post_macro;
533 // These need to be passed upstream as well
534 runparams.need_maketitle = rp.need_maketitle;
535 runparams.have_maketitle = rp.have_maketitle;
537 if (!il.rightdelim().empty())
538 os << il.rightdelim();
540 if (!il.latexname().empty()) {
541 if (il.latextype() == InsetLayout::COMMAND) {
543 if (!il.postcommandargs().empty())
544 getArgs(os, runparams, true);
547 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
548 // A comment environment doesn't need a % before \n\end
549 if (il.isDisplay() || runparams.inComment)
553 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
555 os.protectSpace(true);
558 if (il.forceOwnlines())
563 int InsetText::plaintext(odocstringstream & os,
564 OutputParams const & runparams, size_t max_length) const
566 ParagraphList::const_iterator beg = paragraphs().begin();
567 ParagraphList::const_iterator end = paragraphs().end();
568 ParagraphList::const_iterator it = beg;
569 bool ref_printed = false;
571 for (; it != end; ++it) {
574 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
577 odocstringstream oss;
578 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
579 docstring const str = oss.str();
581 // FIXME: len is not computed fully correctly; in principle,
582 // we have to count the characters after the last '\n'
584 if (os.str().size() >= max_length)
592 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
594 ParagraphList::const_iterator const beg = paragraphs().begin();
597 xml::openTag(os, getLayout().latexname(),
598 beg->getID(buffer(), runparams) + getLayout().latexparam());
600 docbookParagraphs(text_, buffer(), os, runparams);
603 xml::closeTag(os, getLayout().latexname());
609 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
611 return insetAsXHTML(xs, runparams, WriteEverything);
616 // There are cases where we may need to close open fonts and such
617 // and then re-open them when we are done. This would be the case, e.g.,
618 // if we were otherwise about to write:
619 // <em>word <div class='foot'>footnote text.</div> emph</em>
620 // The problem isn't so much that the footnote text will get emphasized:
621 // we can handle that with CSS. The problem is that this is invalid XHTML.
622 // One solution would be to make the footnote <span>, but the problem is
623 // completely general, and so we'd have to make absolutely everything into
624 // span. What I think will work is to check if we're about to write "div" and,
625 // if so, try to close fonts, etc.
626 // There are probably limits to how well we can do here, though, and we will
627 // have to rely upon users not putting footnotes inside noun-type insets.
628 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
629 XHTMLOptions opts) const
631 // we will always want to output all our paragraphs when we are
633 OutputParams runparams = rp;
634 runparams.par_begin = 0;
635 runparams.par_end = text().paragraphs().size();
638 xs.startDivision(false);
639 xhtmlParagraphs(text_, buffer(), xs, runparams);
644 InsetLayout const & il = getLayout();
645 if (opts & WriteOuterTag)
646 xs << xml::StartTag(il.htmltag(), il.htmlattr());
648 if ((opts & WriteLabel) && !il.counter().empty()) {
649 BufferParams const & bp = buffer().masterBuffer()->params();
650 Counters & cntrs = bp.documentClass().counters();
651 cntrs.step(il.counter(), OutputUpdate);
652 // FIXME: translate to paragraph language
653 if (!il.htmllabel().empty()) {
654 docstring const lbl =
655 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
656 // FIXME is this check necessary?
658 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
660 xs << xml::EndTag(il.htmllabeltag());
665 if (opts & WriteInnerTag)
666 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
668 // we will eventually lose information about the containing inset
669 if (!allowMultiPar() || opts == JustText)
670 runparams.html_make_pars = false;
672 runparams.pass_thru = true;
674 xs.startDivision(false);
675 xhtmlParagraphs(text_, buffer(), xs, runparams);
678 if (opts & WriteInnerTag)
679 xs << xml::EndTag(il.htmlinnertag());
681 if (opts & WriteOuterTag)
682 xs << xml::EndTag(il.htmltag());
688 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
689 bool const post) const
691 OutputParams runparams = runparams_in;
692 runparams.local_font =
693 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
695 runparams.pass_thru = true;
697 latexArgInsetsForParent(paragraphs(), os, runparams,
698 getLayout().postcommandargs(), "post:");
700 latexArgInsetsForParent(paragraphs(), os, runparams,
701 getLayout().latexargs());
705 void InsetText::cursorPos(BufferView const & bv,
706 CursorSlice const & sl, bool boundary, int & x, int & y) const
708 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
709 y = bv.textMetrics(&text_).cursorY(sl, boundary);
713 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
716 Paragraph & first = paragraphs().front();
717 for (unsigned int i = 0; i < data.length(); ++i)
718 first.insertChar(i, data[i], font, trackChanges);
722 void InsetText::setDrawFrame(bool flag)
728 ColorCode InsetText::frameColor() const
734 void InsetText::setFrameColor(ColorCode col)
740 void InsetText::appendParagraphs(ParagraphList & plist)
742 // There is little we can do here to keep track of changes.
743 // As of 2006/10/20, appendParagraphs is used exclusively by
744 // LyXTabular::setMultiColumn. In this context, the paragraph break
745 // is lost irreversibly and the appended text doesn't really change
747 ParagraphList & pl = paragraphs();
749 ParagraphList::iterator pit = plist.begin();
750 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
752 mergeParagraph(buffer().params(), pl,
753 distance(pl.begin(), ins) - 1);
755 ParagraphList::iterator const pend = plist.end();
756 for (; pit != pend; ++pit)
761 void InsetText::addPreview(DocIterator const & text_inset_pos,
762 PreviewLoader & loader) const
764 ParagraphList::const_iterator pit = paragraphs().begin();
765 ParagraphList::const_iterator pend = paragraphs().end();
768 DocIterator inset_pos = text_inset_pos;
769 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
771 for (; pit != pend; ++pit, ++pidx) {
772 InsetList::const_iterator it = pit->insetList().begin();
773 InsetList::const_iterator end = pit->insetList().end();
774 inset_pos.pit() = pidx;
775 for (; it != end; ++it) {
776 inset_pos.pos() = it->pos;
777 it->inset->addPreview(inset_pos, loader);
783 ParagraphList const & InsetText::paragraphs() const
785 return text_.paragraphs();
789 ParagraphList & InsetText::paragraphs()
791 return text_.paragraphs();
795 bool InsetText::hasCProtectContent(bool fragile) const
797 fragile |= getLayout().isNeedProtect();
798 ParagraphList const & pars = paragraphs();
799 pit_type pend = pit_type(paragraphs().size());
800 for (pit_type pit = 0; pit != pend; ++pit) {
801 Paragraph const & par = pars[size_type(pit)];
802 if (par.needsCProtection(fragile))
809 bool InsetText::insetAllowed(InsetCode code) const
812 // Arguments and (plain) quotes are also allowed in PassThru insets
817 return !isPassThru();
822 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
824 ParIterator it2 = it;
826 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
827 if (producesOutput()) {
828 InsetLayout const & il = getLayout();
829 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
830 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
832 // LYXERR0("Entering " << name());
833 cnt.clearLastLayout();
834 // FIXME cnt.saveLastCounter()?
836 buffer().updateBuffer(it2, utype, deleted);
838 // LYXERR0("Exiting " << name());
839 cnt.restoreLastLayout();
840 // FIXME cnt.restoreLastCounter()?
842 // Record in this inset is embedded in a title layout
843 // This is needed to decide when \maketitle is output.
844 intitle_context_ = it.paragraph().layout().intitle;
846 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
847 // Note that we do not need to call:
848 // tclass.counters().clearLastLayout()
849 // since we are saving and restoring the existing counters, etc.
850 Counters savecnt = tclass.counters();
851 tclass.counters().reset();
852 // we need float information even in note insets (#9760)
853 tclass.counters().current_float(savecnt.current_float());
854 tclass.counters().isSubfloat(savecnt.isSubfloat());
855 buffer().updateBuffer(it2, utype, deleted);
856 tclass.counters() = move(savecnt);
861 void InsetText::toString(odocstream & os) const
863 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
867 void InsetText::forOutliner(docstring & os, size_t const maxlen,
868 bool const shorten) const
870 if (!getLayout().isInToc())
872 text().forOutliner(os, maxlen, shorten);
876 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
877 UpdateType utype, TocBackend & backend) const
879 DocIterator dit = cdit;
880 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
881 iterateForToc(dit, output_active, utype, backend);
885 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
886 UpdateType utype, TocBackend & backend) const
888 DocIterator dit = cdit;
889 // This also ensures that any document has a table of contents
890 shared_ptr<Toc> toc = backend.toc("tableofcontents");
892 BufferParams const & bufparams = buffer_->params();
893 int const min_toclevel = bufparams.documentClass().min_toclevel();
894 // we really should have done this before we got here, but it
895 // can't hurt too much to do it again
896 bool const doing_output = output_active && producesOutput();
898 // For each paragraph,
899 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
900 // paragraphs as needed.
901 // * Traverse its insets and let them add their toc items
902 // * Compute the main table of contents (this is hardcoded)
903 // * Add the list of changes
904 ParagraphList const & pars = paragraphs();
905 pit_type pend = paragraphs().size();
906 // Record pairs {start,end} of where a toc item was opened for a paragraph
907 // and where it must be closed
908 stack<pair<pit_type, pit_type>> addtotoc_stack;
910 for (pit_type pit = 0; pit != pend; ++pit) {
911 Paragraph const & par = pars[pit];
915 // Custom AddToToc in paragraph layouts (i.e. theorems)
916 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
918 openAddToTocForParagraph(pit, dit, output_active, backend);
919 addtotoc_stack.push({pit, end});
922 // If we find an InsetArgument that is supposed to provide the TOC caption,
923 // we'll save it for use later.
924 InsetArgument const * arginset = nullptr;
925 for (auto const & table : par.insetList()) {
926 dit.pos() = table.pos;
927 table.inset->addToToc(dit, doing_output, utype, backend);
928 if (InsetArgument const * x = table.inset->asInsetArgument())
929 if (x->isTocCaption())
933 // End custom AddToToc in paragraph layouts
934 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
935 // execute the closing function
936 closeAddToTocForParagraph(addtotoc_stack.top().first,
937 addtotoc_stack.top().second, backend);
938 addtotoc_stack.pop();
941 // now the toc entry for the paragraph in the main table of contents
942 int const toclevel = text().getTocLevel(pit);
943 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
944 // insert this into the table of contents
946 int const length = (doing_output && utype == OutputUpdate) ?
947 INT_MAX : TOC_ENTRY_LENGTH;
949 tocstring = par.labelString();
950 if (!tocstring.empty())
952 arginset->text().forOutliner(tocstring, length);
954 par.forOutliner(tocstring, length);
956 toc->push_back(TocItem(dit, toclevel - min_toclevel,
957 tocstring, doing_output));
960 // And now the list of changes.
961 par.addChangesToToc(dit, buffer(), doing_output, backend);
966 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
967 DocIterator const & dit,
969 TocBackend & backend) const
971 Paragraph const & par = paragraphs()[pit];
972 TocBuilder & b = backend.builder(par.layout().tocType());
973 docstring const label = par.labelString();
974 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
975 return text().lastInSequence(pit);
979 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
980 TocBackend & backend) const
982 Paragraph const & par = paragraphs()[start];
983 TocBuilder & b = backend.builder(par.layout().tocType());
984 if (par.layout().isTocCaption()) {
986 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
993 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
995 if (buffer().isClean())
996 return Inset::notifyCursorLeaves(old, cur);
998 // find text inset in old cursor
999 Cursor insetCur = old;
1000 int scriptSlice = insetCur.find(this);
1001 // we can try to continue here. returning true means
1002 // the cursor is "now" invalid. which it was.
1003 LASSERT(scriptSlice != -1, return true);
1004 insetCur.cutOff(scriptSlice);
1005 LASSERT(&insetCur.inset() == this, return true);
1007 // update the old paragraph's words
1008 insetCur.paragraph().updateWords();
1010 return Inset::notifyCursorLeaves(old, cur);
1014 bool InsetText::completionSupported(Cursor const & cur) const
1016 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1017 return text_.completionSupported(cur);
1021 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1023 return completionSupported(cur);
1027 bool InsetText::automaticInlineCompletion() const
1029 return lyxrc.completion_inline_text;
1033 bool InsetText::automaticPopupCompletion() const
1035 return lyxrc.completion_popup_text;
1039 bool InsetText::showCompletionCursor() const
1041 return lyxrc.completion_cursor_text;
1045 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1047 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1051 docstring InsetText::completionPrefix(Cursor const & cur) const
1053 if (!completionSupported(cur))
1055 return text_.completionPrefix(cur);
1059 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1062 if (!completionSupported(cur))
1065 return text_.insertCompletion(cur, s, finished);
1069 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1070 Dimension & dim) const
1072 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1073 tm.completionPosAndDim(cur, x, y, dim);
1077 string InsetText::contextMenu(BufferView const &, int, int) const
1079 string context_menu = contextMenuName();
1080 if (context_menu != InsetText::contextMenuName())
1081 context_menu += ";" + InsetText::contextMenuName();
1082 return context_menu;
1086 string InsetText::contextMenuName() const
1088 return "context-edit";
1092 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1094 OutputParams rp(&buffer().params().encoding());
1095 rp.for_tooltip = true;
1096 odocstringstream oss;
1099 ParagraphList::const_iterator beg = paragraphs().begin();
1100 ParagraphList::const_iterator end = paragraphs().end();
1101 ParagraphList::const_iterator it = beg;
1102 bool ref_printed = false;
1104 for (; it != end; ++it) {
1107 if ((*it).isRTL(buffer().params()))
1108 oss << "<div dir=\"rtl\">";
1109 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1110 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1113 docstring str = oss.str();
1115 str += from_ascii("\n\n") + _("[contains tracked changes]");
1116 support::truncateWithEllipsis(str, len);
1121 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1123 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1127 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1129 // Nested cprotect content needs \cprotect
1131 if (producesOutput() && hasCProtectContent(fragile))
1134 // Environments generally need cprotection in fragile context
1135 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1138 if (!getLayout().needsCProtect())
1141 // Environments and "no latex" types (e.g., knitr chunks)
1142 // need cprotection regardless the content
1143 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1146 // If the inset does not produce output (e.g. Note or Branch),
1147 // we can ignore the contained paragraphs
1148 if (!producesOutput())
1151 // Commands need cprotection if they contain specific chars
1152 int const nchars_escape = 9;
1153 static char_type const chars_escape[nchars_escape] = {
1154 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1156 ParagraphList const & pars = paragraphs();
1157 pit_type pend = pit_type(paragraphs().size());
1159 for (pit_type pit = 0; pit != pend; ++pit) {
1160 Paragraph const & par = pars[size_type(pit)];
1161 if (par.needsCProtection(fragile))
1163 docstring const par_str = par.asString();
1164 for (int k = 0; k < nchars_escape; k++) {
1165 if (contains(par_str, chars_escape[k]))