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/Changer.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 = changeVar(pi.background_color,
233 pi.backgroundColor(this, false));
234 // The change tracking cue must not be inherited
235 Changer dummy2 = changeVar(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);
283 cur.setCurrentFont();
288 Inset * InsetText::editXY(Cursor & cur, int x, int y)
290 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
294 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
296 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
299 // See bug #9042, for instance.
301 // Force any new text to latex_language FIXME: This
302 // should only be necessary in constructor, but new
303 // paragraphs that are created by pressing enter at
304 // the start of an existing paragraph get the buffer
305 // language and not latex_language, so we take this
306 // brute force approach.
307 cur.current_font.setLanguage(latex_language);
308 cur.real_current_font.setLanguage(latex_language);
312 switch (cmd.action()) {
314 case LFUN_CLIPBOARD_PASTE:
315 case LFUN_SELECTION_PASTE:
316 case LFUN_PRIMARY_SELECTION_PASTE:
317 text_.dispatch(cur, cmd);
318 // If we we can only store plain text, we must reset all
320 // FIXME: Change only the pasted paragraphs
324 case LFUN_INSET_DISSOLVE: {
325 bool const main_inset = text_.isMainText();
326 bool const target_inset = cmd.argument().empty()
327 || cmd.getArg(0) == insetName(lyxCode());
329 if (!main_inset && target_inset) {
330 // Text::dissolveInset assumes that the cursor
331 // is inside the Inset.
332 if (&cur.inset() != this)
333 cur.pushBackward(*this);
334 cur.beginUndoGroup();
335 text_.dispatch(cur, cmd);
343 text_.dispatch(cur, cmd);
346 if (!cur.result().dispatched())
347 Inset::doDispatch(cur, cmd);
351 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
352 FuncStatus & status) const
354 switch (cmd.action()) {
355 case LFUN_INSET_DISSOLVE: {
356 bool const main_inset = text_.isMainText();
357 bool const target_inset = cmd.argument().empty()
358 || cmd.getArg(0) == insetName(lyxCode());
361 status.setEnabled(!main_inset);
365 case LFUN_ARGUMENT_INSERT: {
366 string const arg = cmd.getArg(0);
368 status.setEnabled(false);
371 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
372 return text_.getStatus(cur, cmd, status);
374 Layout::LaTeXArgMap args = getLayout().args();
375 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
376 if (lait != args.end()) {
377 status.setEnabled(true);
378 for (Paragraph const & par : paragraphs())
379 for (auto const & table : par.insetList())
380 if (InsetArgument const * ins = table.inset->asInsetArgument())
381 if (ins->name() == arg) {
382 // we have this already
383 status.setEnabled(false);
387 status.setEnabled(false);
392 // Dispatch only to text_ if the cursor is inside
393 // the text_. It is not for context menus (bug 5797).
395 if (cur.text() == &text_)
396 ret = text_.getStatus(cur, cmd, status);
399 ret = Inset::getStatus(cur, cmd, status);
405 void InsetText::fixParagraphsFont()
407 Font font(inherit_font, buffer().params().language);
408 font.setLanguage(latex_language);
409 ParagraphList::iterator par = paragraphs().begin();
410 ParagraphList::iterator const end = paragraphs().end();
412 if (par->isPassThru())
413 par->resetFonts(font);
414 if (!par->allowParagraphCustomization())
415 par->params().clear();
421 // bool InsetText::isChanged() const
423 // ParagraphList::const_iterator pit = paragraphs().begin();
424 // ParagraphList::const_iterator end = paragraphs().end();
425 // for (; pit != end; ++pit) {
426 // if (pit->isChanged())
433 void InsetText::setChange(Change const & change)
435 ParagraphList::iterator pit = paragraphs().begin();
436 ParagraphList::iterator end = paragraphs().end();
437 for (; pit != end; ++pit) {
438 pit->setChange(change);
443 void InsetText::acceptChanges()
445 text_.acceptChanges();
449 void InsetText::rejectChanges()
451 text_.rejectChanges();
455 void InsetText::validate(LaTeXFeatures & features) const
457 features.useInsetLayout(getLayout());
458 for (Paragraph const & p : paragraphs())
459 p.validate(features);
463 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
465 // This implements the standard way of handling the LaTeX
466 // output of a text inset, either a command or an
467 // environment. Standard collapsible insets should not
468 // redefine this, non-standard ones may call this.
469 InsetLayout const & il = getLayout();
470 if (il.forceOwnlines())
472 bool needendgroup = false;
473 if (!il.latexname().empty()) {
474 if (il.latextype() == InsetLayout::COMMAND) {
476 // FIXME \protect should only be used for fragile
477 // commands, but we do not provide this information yet.
478 if (hasCProtectContent(runparams.moving_arg)) {
479 if (contains(runparams.active_chars, '^')) {
480 // cprotect relies on ^ being on catcode 7
481 os << "\\begingroup\\catcode`\\^=7";
485 } else if (runparams.moving_arg)
487 os << '\\' << from_utf8(il.latexname());
488 if (!il.latexargs().empty())
489 getArgs(os, runparams);
490 if (!il.latexparam().empty())
491 os << from_utf8(il.latexparam());
493 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
498 if (runparams.lastid != -1)
499 os.texrow().start(runparams.lastid,
501 os << "\\begin{" << from_utf8(il.latexname()) << "}";
502 if (!il.latexargs().empty())
503 getArgs(os, runparams);
504 if (!il.latexparam().empty())
505 os << from_utf8(il.latexparam());
509 if (!il.latexargs().empty())
510 getArgs(os, runparams);
511 if (!il.latexparam().empty())
512 os << from_utf8(il.latexparam());
515 if (!il.leftdelim().empty())
516 os << il.leftdelim();
518 OutputParams rp = runparams;
521 if (il.isNeedProtect())
522 rp.moving_arg = true;
523 if (il.isNeedMBoxProtect())
525 if (!il.passThruChars().empty())
526 rp.pass_thru_chars += il.passThruChars();
527 if (!il.newlineCmd().empty())
528 rp.newlinecmd = il.newlineCmd();
530 rp.par_end = paragraphs().size();
532 // Output the contents of the inset
533 latexParagraphs(buffer(), text_, os, rp);
534 runparams.encoding = rp.encoding;
535 // Pass the post_macros upstream
536 runparams.post_macro = rp.post_macro;
537 // These need to be passed upstream as well
538 runparams.need_maketitle = rp.need_maketitle;
539 runparams.have_maketitle = rp.have_maketitle;
541 if (!il.rightdelim().empty())
542 os << il.rightdelim();
544 if (!il.latexname().empty()) {
545 if (il.latextype() == InsetLayout::COMMAND) {
547 if (!il.postcommandargs().empty())
548 getArgs(os, runparams, true);
551 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
552 // A comment environment doesn't need a % before \n\end
553 if (il.isDisplay() || runparams.inComment)
557 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
559 os.protectSpace(true);
562 if (il.forceOwnlines())
567 int InsetText::plaintext(odocstringstream & os,
568 OutputParams const & runparams, size_t max_length) const
570 ParagraphList::const_iterator beg = paragraphs().begin();
571 ParagraphList::const_iterator end = paragraphs().end();
572 ParagraphList::const_iterator it = beg;
573 bool ref_printed = false;
575 for (; it != end; ++it) {
578 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
581 odocstringstream oss;
582 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
583 docstring const str = oss.str();
585 // FIXME: len is not computed fully correctly; in principle,
586 // we have to count the characters after the last '\n'
588 if (os.str().size() >= max_length)
597 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
599 docbook(xs, rp, WriteEverything);
603 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
605 // we will always want to output all our paragraphs when we are
607 OutputParams runparams = rp;
608 runparams.par_begin = 0;
609 runparams.par_end = text().paragraphs().size();
612 xs.startDivision(false);
613 docbookParagraphs(text_, buffer(), xs, runparams);
618 InsetLayout const & il = getLayout();
620 // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
621 // else, typically outside the current paragraph).
622 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
625 // Start outputting this inset.
626 if (opts & WriteOuterTag) {
627 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
628 xs << xml::StartTag(il.docbookwrappertag(), il.docbookwrapperattr());
630 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
631 docstring attrs = docstring();
632 if (!il.docbookattr().empty())
633 attrs += from_ascii(il.docbookattr());
634 if (il.docbooktag() == "link")
635 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
636 xs << xml::StartTag(il.docbooktag(), attrs);
639 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
640 xs << xml::StartTag(il.docbookitemwrappertag(), il.docbookitemwrapperattr());
642 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
643 xs << xml::StartTag(il.docbookitemtag(), il.docbookitemattr());
646 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
648 // With respect to XHTML, paragraphs are still allowed here.
649 if (!allowMultiPar())
650 runparams.docbook_make_pars = false;
652 runparams.pass_thru = true;
654 xs.startDivision(false);
655 docbookParagraphs(text_, buffer(), xs, runparams);
658 if (opts & WriteOuterTag) {
659 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
660 xs << xml::EndTag(il.docbookitemtag());
662 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
663 xs << xml::EndTag(il.docbookitemwrappertag());
665 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
666 xs << xml::EndTag(il.docbooktag());
668 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
669 xs << xml::EndTag(il.docbookwrappertag());
674 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
676 return insetAsXHTML(xs, runparams, WriteEverything);
681 // There are cases where we may need to close open fonts and such
682 // and then re-open them when we are done. This would be the case, e.g.,
683 // if we were otherwise about to write:
684 // <em>word <div class='foot'>footnote text.</div> emph</em>
685 // The problem isn't so much that the footnote text will get emphasized:
686 // we can handle that with CSS. The problem is that this is invalid XHTML.
687 // One solution would be to make the footnote <span>, but the problem is
688 // completely general, and so we'd have to make absolutely everything into
689 // span. What I think will work is to check if we're about to write "div" and,
690 // if so, try to close fonts, etc.
691 // There are probably limits to how well we can do here, though, and we will
692 // have to rely upon users not putting footnotes inside noun-type insets.
693 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
694 XHTMLOptions opts) const
696 // we will always want to output all our paragraphs when we are
698 OutputParams runparams = rp;
699 runparams.par_begin = 0;
700 runparams.par_end = text().paragraphs().size();
703 xs.startDivision(false);
704 xhtmlParagraphs(text_, buffer(), xs, runparams);
709 InsetLayout const & il = getLayout();
710 if (opts & WriteOuterTag)
711 xs << xml::StartTag(il.htmltag(), il.htmlattr());
713 if ((opts & WriteLabel) && !il.counter().empty()) {
714 BufferParams const & bp = buffer().masterBuffer()->params();
715 Counters & cntrs = bp.documentClass().counters();
716 cntrs.step(il.counter(), OutputUpdate);
717 // FIXME: translate to paragraph language
718 if (!il.htmllabel().empty()) {
719 docstring const lbl =
720 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
721 // FIXME is this check necessary?
723 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
725 xs << xml::EndTag(il.htmllabeltag());
730 if (opts & WriteInnerTag)
731 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
733 // we will eventually lose information about the containing inset
734 if (!allowMultiPar() || opts == JustText)
735 runparams.html_make_pars = false;
737 runparams.pass_thru = true;
739 xs.startDivision(false);
740 xhtmlParagraphs(text_, buffer(), xs, runparams);
743 if (opts & WriteInnerTag)
744 xs << xml::EndTag(il.htmlinnertag());
746 if (opts & WriteOuterTag)
747 xs << xml::EndTag(il.htmltag());
753 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
754 bool const post) const
756 OutputParams runparams = runparams_in;
757 runparams.local_font =
758 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
760 runparams.pass_thru = true;
762 latexArgInsetsForParent(paragraphs(), os, runparams,
763 getLayout().postcommandargs(), "post:");
765 latexArgInsetsForParent(paragraphs(), os, runparams,
766 getLayout().latexargs());
770 void InsetText::cursorPos(BufferView const & bv,
771 CursorSlice const & sl, bool boundary, int & x, int & y) const
773 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
774 y = bv.textMetrics(&text_).cursorY(sl, boundary);
778 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
781 Paragraph & first = paragraphs().front();
782 for (unsigned int i = 0; i < data.length(); ++i)
783 first.insertChar(i, data[i], font, trackChanges);
787 void InsetText::setDrawFrame(bool flag)
793 ColorCode InsetText::frameColor() const
799 void InsetText::setFrameColor(ColorCode col)
805 void InsetText::appendParagraphs(ParagraphList & plist)
807 // There is little we can do here to keep track of changes.
808 // As of 2006/10/20, appendParagraphs is used exclusively by
809 // LyXTabular::setMultiColumn. In this context, the paragraph break
810 // is lost irreversibly and the appended text doesn't really change
812 ParagraphList & pl = paragraphs();
814 ParagraphList::iterator pit = plist.begin();
815 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
817 mergeParagraph(buffer().params(), pl,
818 distance(pl.begin(), ins) - 1);
820 ParagraphList::iterator const pend = plist.end();
821 for (; pit != pend; ++pit)
826 void InsetText::addPreview(DocIterator const & text_inset_pos,
827 PreviewLoader & loader) const
829 ParagraphList::const_iterator pit = paragraphs().begin();
830 ParagraphList::const_iterator pend = paragraphs().end();
833 DocIterator inset_pos = text_inset_pos;
834 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
836 for (; pit != pend; ++pit, ++pidx) {
837 InsetList::const_iterator it = pit->insetList().begin();
838 InsetList::const_iterator end = pit->insetList().end();
839 inset_pos.pit() = pidx;
840 for (; it != end; ++it) {
841 inset_pos.pos() = it->pos;
842 it->inset->addPreview(inset_pos, loader);
848 ParagraphList const & InsetText::paragraphs() const
850 return text_.paragraphs();
854 ParagraphList & InsetText::paragraphs()
856 return text_.paragraphs();
860 bool InsetText::hasCProtectContent(bool fragile) const
862 fragile |= getLayout().isNeedProtect();
863 ParagraphList const & pars = paragraphs();
864 pit_type pend = pit_type(paragraphs().size());
865 for (pit_type pit = 0; pit != pend; ++pit) {
866 Paragraph const & par = pars[size_type(pit)];
867 if (par.needsCProtection(fragile))
874 bool InsetText::insetAllowed(InsetCode code) const
877 // Arguments and (plain) quotes are also allowed in PassThru insets
882 return !isPassThru();
887 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
889 ParIterator it2 = it;
891 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
892 if (producesOutput()) {
893 InsetLayout const & il = getLayout();
894 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
895 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
897 // LYXERR0("Entering " << name());
898 cnt.clearLastLayout();
899 // FIXME cnt.saveLastCounter()?
901 buffer().updateBuffer(it2, utype, deleted);
903 // LYXERR0("Exiting " << name());
904 cnt.restoreLastLayout();
905 // FIXME cnt.restoreLastCounter()?
907 // Record in this inset is embedded in a title layout
908 // This is needed to decide when \maketitle is output.
909 intitle_context_ = it.paragraph().layout().intitle;
910 // Also check embedding layouts
911 size_t const n = it.depth();
912 for (size_t i = 0; i < n; ++i) {
913 if (it[i].paragraph().layout().intitle) {
914 intitle_context_ = true;
919 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
920 // Note that we do not need to call:
921 // tclass.counters().clearLastLayout()
922 // since we are saving and restoring the existing counters, etc.
923 Counters savecnt = tclass.counters();
924 tclass.counters().reset();
925 // we need float information even in note insets (#9760)
926 tclass.counters().current_float(savecnt.current_float());
927 tclass.counters().isSubfloat(savecnt.isSubfloat());
928 buffer().updateBuffer(it2, utype, deleted);
929 tclass.counters() = move(savecnt);
934 void InsetText::toString(odocstream & os) const
936 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
940 void InsetText::forOutliner(docstring & os, size_t const maxlen,
941 bool const shorten) const
943 if (!getLayout().isInToc())
945 text().forOutliner(os, maxlen, shorten);
949 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
950 UpdateType utype, TocBackend & backend) const
952 DocIterator dit = cdit;
953 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
954 iterateForToc(dit, output_active, utype, backend);
958 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
959 UpdateType utype, TocBackend & backend) const
961 DocIterator dit = cdit;
962 // This also ensures that any document has a table of contents
963 shared_ptr<Toc> toc = backend.toc("tableofcontents");
965 BufferParams const & bufparams = buffer_->params();
966 int const min_toclevel = bufparams.documentClass().min_toclevel();
967 // we really should have done this before we got here, but it
968 // can't hurt too much to do it again
969 bool const doing_output = output_active && producesOutput();
971 // For each paragraph,
972 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
973 // paragraphs as needed.
974 // * Traverse its insets and let them add their toc items
975 // * Compute the main table of contents (this is hardcoded)
976 // * Add the list of changes
977 ParagraphList const & pars = paragraphs();
978 pit_type pend = paragraphs().size();
979 // Record pairs {start,end} of where a toc item was opened for a paragraph
980 // and where it must be closed
981 stack<pair<pit_type, pit_type>> addtotoc_stack;
983 for (pit_type pit = 0; pit != pend; ++pit) {
984 Paragraph const & par = pars[pit];
988 // Custom AddToToc in paragraph layouts (i.e. theorems)
989 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
991 openAddToTocForParagraph(pit, dit, output_active, backend);
992 addtotoc_stack.push({pit, end});
995 // If we find an InsetArgument that is supposed to provide the TOC caption,
996 // we'll save it for use later.
997 InsetArgument const * arginset = nullptr;
998 for (auto const & table : par.insetList()) {
999 dit.pos() = table.pos;
1000 table.inset->addToToc(dit, doing_output, utype, backend);
1001 if (InsetArgument const * x = table.inset->asInsetArgument())
1002 if (x->isTocCaption())
1006 // End custom AddToToc in paragraph layouts
1007 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1008 // execute the closing function
1009 closeAddToTocForParagraph(addtotoc_stack.top().first,
1010 addtotoc_stack.top().second, backend);
1011 addtotoc_stack.pop();
1014 // now the toc entry for the paragraph in the main table of contents
1015 int const toclevel = text().getTocLevel(pit);
1016 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1017 // insert this into the table of contents
1018 docstring tocstring;
1019 int const length = (doing_output && utype == OutputUpdate) ?
1020 INT_MAX : TOC_ENTRY_LENGTH;
1022 tocstring = par.labelString();
1023 if (!tocstring.empty())
1025 arginset->text().forOutliner(tocstring, length);
1027 par.forOutliner(tocstring, length);
1029 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1030 tocstring, doing_output));
1033 // And now the list of changes.
1034 par.addChangesToToc(dit, buffer(), doing_output, backend);
1039 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1040 DocIterator const & dit,
1042 TocBackend & backend) const
1044 Paragraph const & par = paragraphs()[pit];
1045 TocBuilder & b = backend.builder(par.layout().tocType());
1046 docstring const & label = par.labelString();
1047 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1048 return text().lastInSequence(pit);
1052 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1053 TocBackend & backend) const
1055 Paragraph const & par = paragraphs()[start];
1056 TocBuilder & b = backend.builder(par.layout().tocType());
1057 if (par.layout().isTocCaption()) {
1059 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1060 b.argumentItem(str);
1066 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1068 if (buffer().isClean())
1069 return Inset::notifyCursorLeaves(old, cur);
1071 // find text inset in old cursor
1072 Cursor insetCur = old;
1073 int scriptSlice = insetCur.find(this);
1074 // we can try to continue here. returning true means
1075 // the cursor is "now" invalid. which it was.
1076 LASSERT(scriptSlice != -1, return true);
1077 insetCur.cutOff(scriptSlice);
1078 LASSERT(&insetCur.inset() == this, return true);
1080 // update the old paragraph's words
1081 insetCur.paragraph().updateWords();
1083 return Inset::notifyCursorLeaves(old, cur);
1087 bool InsetText::completionSupported(Cursor const & cur) const
1089 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1090 return text_.completionSupported(cur);
1094 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1096 return completionSupported(cur);
1100 bool InsetText::automaticInlineCompletion() const
1102 return lyxrc.completion_inline_text;
1106 bool InsetText::automaticPopupCompletion() const
1108 return lyxrc.completion_popup_text;
1112 bool InsetText::showCompletionCursor() const
1114 return lyxrc.completion_cursor_text;
1118 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1120 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1124 docstring InsetText::completionPrefix(Cursor const & cur) const
1126 if (!completionSupported(cur))
1128 return text_.completionPrefix(cur);
1132 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1135 if (!completionSupported(cur))
1138 return text_.insertCompletion(cur, s, finished);
1142 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1143 Dimension & dim) const
1145 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1146 tm.completionPosAndDim(cur, x, y, dim);
1150 string InsetText::contextMenu(BufferView const &, int, int) const
1152 string context_menu = contextMenuName();
1153 if (context_menu != InsetText::contextMenuName())
1154 context_menu += ";" + InsetText::contextMenuName();
1155 return context_menu;
1159 string InsetText::contextMenuName() const
1161 return "context-edit";
1165 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1167 OutputParams rp(&buffer().params().encoding());
1168 rp.for_tooltip = true;
1169 odocstringstream oss;
1172 ParagraphList::const_iterator beg = paragraphs().begin();
1173 ParagraphList::const_iterator end = paragraphs().end();
1174 ParagraphList::const_iterator it = beg;
1175 bool ref_printed = false;
1177 for (; it != end; ++it) {
1180 if ((*it).isRTL(buffer().params()))
1181 oss << "<div dir=\"rtl\">";
1182 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1183 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1186 docstring str = oss.str();
1188 str += from_ascii("\n\n") + _("[contains tracked changes]");
1189 support::truncateWithEllipsis(str, len);
1194 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1196 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1200 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1202 // Nested cprotect content needs \cprotect
1204 if (producesOutput() && hasCProtectContent(fragile))
1207 // Environments generally need cprotection in fragile context
1208 if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1211 if (!getLayout().needsCProtect())
1214 // Environments and "no latex" types (e.g., knitr chunks)
1215 // need cprotection regardless the content
1216 if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1219 // If the inset does not produce output (e.g. Note or Branch),
1220 // we can ignore the contained paragraphs
1221 if (!producesOutput())
1224 // Commands need cprotection if they contain specific chars
1225 int const nchars_escape = 9;
1226 static char_type const chars_escape[nchars_escape] = {
1227 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1229 ParagraphList const & pars = paragraphs();
1230 pit_type pend = pit_type(paragraphs().size());
1232 for (pit_type pit = 0; pit != pend; ++pit) {
1233 Paragraph const & par = pars[size_type(pit)];
1234 if (par.needsCProtection(fragile))
1236 docstring const par_str = par.asString();
1237 for (int k = 0; k < nchars_escape; k++) {
1238 if (contains(par_str, chars_escape[k]))