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 "InsetLayout.h"
14 #include "InsetText.h"
16 #include "insets/InsetArgument.h"
17 #include "insets/InsetLayout.h"
19 #include "buffer_funcs.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "CompletionList.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "InsetList.h"
35 #include "LaTeXFeatures.h"
39 #include "MetricsInfo.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_plaintext.h"
43 #include "output_xhtml.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
48 #include "texstream.h"
49 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53 #include "TocBuilder.h"
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/Changer.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 = changeVar(pi.background_color,
232 pi.backgroundColor(this, false));
233 // The change tracking cue must not be inherited
234 Changer dummy2 = changeVar(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);
282 cur.setCurrentFont();
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);
298 // See bug #9042, for instance.
300 // Force any new text to latex_language FIXME: This
301 // should only be necessary in constructor, but new
302 // paragraphs that are created by pressing enter at
303 // the start of an existing paragraph get the buffer
304 // language and not latex_language, so we take this
305 // brute force approach.
306 cur.current_font.setLanguage(latex_language);
307 cur.real_current_font.setLanguage(latex_language);
311 switch (cmd.action()) {
313 case LFUN_CLIPBOARD_PASTE:
314 case LFUN_SELECTION_PASTE:
315 case LFUN_PRIMARY_SELECTION_PASTE:
316 text_.dispatch(cur, cmd);
317 // If we we can only store plain text, we must reset all
319 // FIXME: Change only the pasted paragraphs
323 case LFUN_INSET_SPLIT:
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 UndoGroupHelper ugh(&buffer());
331 // Text::dissolveInset assumes that the cursor
332 // is inside the Inset.
333 if (&cur.inset() != this) {
335 cur.pushBackward(*this);
337 text_.dispatch(cur, cmd);
344 text_.dispatch(cur, cmd);
347 if (!cur.result().dispatched())
348 Inset::doDispatch(cur, cmd);
352 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
353 FuncStatus & status) const
355 switch (cmd.action()) {
356 case LFUN_INSET_SPLIT:
357 case LFUN_INSET_DISSOLVE: {
358 bool const main_inset = text_.isMainText();
359 bool const target_inset = cmd.argument().empty()
360 || cmd.getArg(0) == insetName(lyxCode());
363 status.setEnabled(!main_inset);
367 case LFUN_ARGUMENT_INSERT: {
368 string const arg = cmd.getArg(0);
370 status.setEnabled(false);
373 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
374 return text_.getStatus(cur, cmd, status);
376 Layout::LaTeXArgMap args = getLayout().args();
377 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
378 if (lait != args.end()) {
379 status.setEnabled(true);
380 for (Paragraph const & par : paragraphs())
381 for (auto const & table : par.insetList())
382 if (InsetArgument const * ins = table.inset->asInsetArgument())
383 if (ins->name() == arg) {
384 // we have this already
385 status.setEnabled(false);
389 status.setEnabled(false);
394 // Dispatch only to text_ if the cursor is inside
395 // the text_. It is not for context menus (bug 5797).
397 if (cur.text() == &text_)
398 ret = text_.getStatus(cur, cmd, status);
401 ret = Inset::getStatus(cur, cmd, status);
407 void InsetText::fixParagraphsFont()
409 Font font(inherit_font, buffer().params().language);
410 font.setLanguage(latex_language);
411 ParagraphList::iterator par = paragraphs().begin();
412 ParagraphList::iterator const end = paragraphs().end();
414 if (par->isPassThru())
415 par->resetFonts(font);
416 if (!par->allowParagraphCustomization())
417 par->params().clear();
423 // bool InsetText::isChanged() const
425 // ParagraphList::const_iterator pit = paragraphs().begin();
426 // ParagraphList::const_iterator end = paragraphs().end();
427 // for (; pit != end; ++pit) {
428 // if (pit->isChanged())
435 void InsetText::setChange(Change const & change)
437 ParagraphList::iterator pit = paragraphs().begin();
438 ParagraphList::iterator end = paragraphs().end();
439 for (; pit != end; ++pit) {
440 pit->setChange(change);
445 void InsetText::acceptChanges()
447 text_.acceptChanges();
451 void InsetText::rejectChanges()
453 text_.rejectChanges();
457 void InsetText::validate(LaTeXFeatures & features) const
459 features.useInsetLayout(getLayout());
460 for (Paragraph const & p : paragraphs())
461 p.validate(features);
465 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
467 // This implements the standard way of handling the LaTeX
468 // output of a text inset, either a command or an
469 // environment. Standard collapsible insets should not
470 // redefine this, non-standard ones may call this.
471 InsetLayout const & il = getLayout();
472 if (il.forceOwnlines())
474 bool needendgroup = false;
475 if (!il.latexname().empty()) {
476 if (il.latextype() == InsetLaTeXType::COMMAND) {
478 // FIXME \protect should only be used for fragile
479 // commands, but we do not provide this information yet.
480 if (hasCProtectContent(runparams.moving_arg)) {
481 if (contains(runparams.active_chars, '^')) {
482 // cprotect relies on ^ being on catcode 7
483 os << "\\begingroup\\catcode`\\^=7";
487 } else if (runparams.moving_arg)
489 os << '\\' << from_utf8(il.latexname());
490 if (!il.latexargs().empty())
491 getArgs(os, runparams);
492 if (!il.latexparam().empty())
493 os << from_utf8(il.latexparam());
495 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
500 if (runparams.lastid != -1)
501 os.texrow().start(runparams.lastid,
503 os << "\\begin{" << from_utf8(il.latexname()) << "}";
504 if (!il.latexargs().empty())
505 getArgs(os, runparams);
506 if (!il.latexparam().empty())
507 os << from_utf8(il.latexparam());
511 if (!il.latexargs().empty())
512 getArgs(os, runparams);
513 if (!il.latexparam().empty())
514 os << from_utf8(il.latexparam());
517 if (!il.leftdelim().empty())
518 os << il.leftdelim();
520 OutputParams rp = runparams;
523 if (il.isNeedProtect())
524 rp.moving_arg = true;
525 if (il.isNeedMBoxProtect())
527 if (!il.passThruChars().empty())
528 rp.pass_thru_chars += il.passThruChars();
529 if (!il.newlineCmd().empty())
530 rp.newlinecmd = il.newlineCmd();
532 rp.par_end = paragraphs().size();
534 // Output the contents of the inset
535 latexParagraphs(buffer(), text_, os, rp);
536 runparams.encoding = rp.encoding;
537 // Pass the post_macros upstream
538 runparams.post_macro = rp.post_macro;
539 // These need to be passed upstream as well
540 runparams.need_maketitle = rp.need_maketitle;
541 runparams.have_maketitle = rp.have_maketitle;
543 if (!il.rightdelim().empty())
544 os << il.rightdelim();
546 if (!il.latexname().empty()) {
547 if (il.latextype() == InsetLaTeXType::COMMAND) {
549 if (!il.postcommandargs().empty())
550 getArgs(os, runparams, true);
553 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
554 // A comment environment doesn't need a % before \n\end
555 if (il.isDisplay() || runparams.inComment)
559 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
561 os.protectSpace(true);
564 if (il.forceOwnlines())
569 int InsetText::plaintext(odocstringstream & os,
570 OutputParams const & runparams, size_t max_length) const
572 ParagraphList::const_iterator beg = paragraphs().begin();
573 ParagraphList::const_iterator end = paragraphs().end();
574 ParagraphList::const_iterator it = beg;
575 bool ref_printed = false;
577 for (; it != end; ++it) {
580 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
583 odocstringstream oss;
584 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
585 docstring const str = oss.str();
587 // FIXME: len is not computed fully correctly; in principle,
588 // we have to count the characters after the last '\n'
590 if (os.str().size() >= max_length)
599 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
601 docbook(xs, rp, WriteEverything);
605 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
607 // we will always want to output all our paragraphs when we are
609 OutputParams runparams = rp;
610 runparams.par_begin = 0;
611 runparams.par_end = text().paragraphs().size();
614 xs.startDivision(false);
615 docbookParagraphs(text_, buffer(), xs, runparams);
620 InsetLayout const & il = getLayout();
622 // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
623 // else, typically outside the current paragraph).
624 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
627 // In some cases, the input parameters must be overridden for outer tags.
628 bool writeOuterTag = opts & WriteOuterTag;
630 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
631 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
632 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
633 auto parSize = (size_t) par.size();
634 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
636 writeOuterTag = !allBibitems;
639 // Detect arguments that should be output before/after the paragraph.
640 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
641 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
642 std::set<InsetArgument const *> prependedArguments;
643 for (auto const & par : paragraphs()) {
644 for (pos_type i = 0; i < par.size(); ++i) {
645 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
646 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
647 if (arg->docbookargumentbeforemaintag())
648 prependedArguments.insert(par.getInset(i)->asInsetArgument());
653 std::set<InsetArgument const *> appendedArguments;
654 for (auto const & par : paragraphs()) {
655 for (pos_type i = 0; i < par.size(); ++i) {
656 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
657 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
658 if (arg->docbookargumentaftermaintag())
659 appendedArguments.insert(par.getInset(i)->asInsetArgument());
664 // Start outputting this inset.
665 // - First, wrapper around the inset and its main tag.
667 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
668 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
670 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
671 docstring attrs = docstring();
672 if (!il.docbookattr().empty())
673 attrs += from_ascii(il.docbookattr());
674 if (il.docbooktag() == "link")
675 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
676 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
680 // - Think about the arguments before the paragraph.
681 OutputParams np = runparams;
682 np.docbook_in_par = true;
683 for (auto const & arg : prependedArguments)
684 arg->docbook(xs, np);
686 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
687 runparams.docbook_prepended_arguments = std::move(prependedArguments);
688 runparams.docbook_appended_arguments = appendedArguments;
690 // - Deal with the first item.
691 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
693 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
694 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
696 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
697 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
700 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
702 // With respect to XHTML, paragraphs are still allowed here.
703 if (!allowMultiPar())
704 runparams.docbook_make_pars = false;
706 runparams.pass_thru = true;
708 // - Write the main content of the inset.
709 xs.startDivision(false);
710 docbookParagraphs(text_, buffer(), xs, runparams);
713 // - Think about the arguments after the paragraph.
714 for (auto const & arg : appendedArguments)
715 arg->docbook(xs, np);
717 // - Close the required tags.
719 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
720 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
722 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
723 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
725 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
726 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
728 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
729 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
734 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
736 return insetAsXHTML(xs, runparams, WriteEverything);
741 // There are cases where we may need to close open fonts and such
742 // and then re-open them when we are done. This would be the case, e.g.,
743 // if we were otherwise about to write:
744 // <em>word <div class='foot'>footnote text.</div> emph</em>
745 // The problem isn't so much that the footnote text will get emphasized:
746 // we can handle that with CSS. The problem is that this is invalid XHTML.
747 // One solution would be to make the footnote <span>, but the problem is
748 // completely general, and so we'd have to make absolutely everything into
749 // span. What I think will work is to check if we're about to write "div" and,
750 // if so, try to close fonts, etc.
751 // There are probably limits to how well we can do here, though, and we will
752 // have to rely upon users not putting footnotes inside noun-type insets.
753 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
754 XHTMLOptions opts) const
756 // we will always want to output all our paragraphs when we are
758 OutputParams runparams = rp;
759 runparams.par_begin = 0;
760 runparams.par_end = text().paragraphs().size();
763 xs.startDivision(false);
764 xhtmlParagraphs(text_, buffer(), xs, runparams);
769 InsetLayout const & il = getLayout();
770 if (opts & WriteOuterTag)
771 xs << xml::StartTag(il.htmltag(), il.htmlattr());
773 if ((opts & WriteLabel) && !il.counter().empty()) {
774 BufferParams const & bp = buffer().masterBuffer()->params();
775 Counters & cntrs = bp.documentClass().counters();
776 cntrs.step(il.counter(), OutputUpdate);
777 // FIXME: translate to paragraph language
778 if (!il.htmllabel().empty()) {
779 docstring const lbl =
780 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
781 // FIXME is this check necessary?
783 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
785 xs << xml::EndTag(il.htmllabeltag());
790 if (opts & WriteInnerTag)
791 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
793 // we will eventually lose information about the containing inset
794 if (!allowMultiPar() || opts == JustText)
795 runparams.html_make_pars = false;
797 runparams.pass_thru = true;
799 xs.startDivision(false);
800 xhtmlParagraphs(text_, buffer(), xs, runparams);
803 if (opts & WriteInnerTag)
804 xs << xml::EndTag(il.htmlinnertag());
806 if (opts & WriteOuterTag)
807 xs << xml::EndTag(il.htmltag());
813 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
814 bool const post) const
816 OutputParams runparams = runparams_in;
817 runparams.local_font =
818 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
820 runparams.pass_thru = true;
822 latexArgInsetsForParent(paragraphs(), os, runparams,
823 getLayout().postcommandargs(), "post:");
825 latexArgInsetsForParent(paragraphs(), os, runparams,
826 getLayout().latexargs());
830 void InsetText::cursorPos(BufferView const & bv,
831 CursorSlice const & sl, bool boundary, int & x, int & y) const
833 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
834 y = bv.textMetrics(&text_).cursorY(sl, boundary);
838 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
841 Paragraph & first = paragraphs().front();
842 for (unsigned int i = 0; i < data.length(); ++i)
843 first.insertChar(i, data[i], font, trackChanges);
847 void InsetText::setDrawFrame(bool flag)
853 ColorCode InsetText::frameColor() const
859 void InsetText::setFrameColor(ColorCode col)
865 void InsetText::appendParagraphs(ParagraphList & plist)
867 // There is little we can do here to keep track of changes.
868 // As of 2006/10/20, appendParagraphs is used exclusively by
869 // LyXTabular::setMultiColumn. In this context, the paragraph break
870 // is lost irreversibly and the appended text doesn't really change
872 ParagraphList & pl = paragraphs();
874 ParagraphList::iterator pit = plist.begin();
875 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
877 mergeParagraph(buffer().params(), pl,
878 distance(pl.begin(), ins) - 1);
880 ParagraphList::iterator const pend = plist.end();
881 for (; pit != pend; ++pit)
886 void InsetText::addPreview(DocIterator const & text_inset_pos,
887 PreviewLoader & loader) const
889 ParagraphList::const_iterator pit = paragraphs().begin();
890 ParagraphList::const_iterator pend = paragraphs().end();
893 DocIterator inset_pos = text_inset_pos;
894 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
896 for (; pit != pend; ++pit, ++pidx) {
897 InsetList::const_iterator it = pit->insetList().begin();
898 InsetList::const_iterator end = pit->insetList().end();
899 inset_pos.pit() = pidx;
900 for (; it != end; ++it) {
901 inset_pos.pos() = it->pos;
902 it->inset->addPreview(inset_pos, loader);
908 ParagraphList const & InsetText::paragraphs() const
910 return text_.paragraphs();
914 ParagraphList & InsetText::paragraphs()
916 return text_.paragraphs();
920 bool InsetText::hasCProtectContent(bool fragile) const
922 fragile |= getLayout().isNeedProtect();
923 ParagraphList const & pars = paragraphs();
924 pit_type pend = pit_type(paragraphs().size());
925 for (pit_type pit = 0; pit != pend; ++pit) {
926 Paragraph const & par = pars[size_type(pit)];
927 if (par.needsCProtection(fragile))
934 bool InsetText::insetAllowed(InsetCode code) const
937 // Arguments and (plain) quotes are also allowed in PassThru insets
942 return !isPassThru();
947 bool InsetText::allowSpellCheck() const
949 return getLayout().spellcheck() && !getLayout().isPassThru();
953 bool InsetText::allowMultiPar() const
955 return getLayout().isMultiPar();
959 bool InsetText::forcePlainLayout(idx_type) const
961 return getLayout().forcePlainLayout();
965 bool InsetText::allowParagraphCustomization(idx_type) const
967 return getLayout().allowParagraphCustomization();
971 bool InsetText::forceLocalFontSwitch() const
973 return getLayout().forceLocalFontSwitch();
977 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
979 ParIterator it2 = it;
981 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
982 if (producesOutput()) {
983 InsetLayout const & il = getLayout();
984 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
985 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
987 // LYXERR0("Entering " << name());
988 cnt.clearLastLayout();
989 // FIXME cnt.saveLastCounter()?
991 buffer().updateBuffer(it2, utype, deleted);
993 // LYXERR0("Exiting " << name());
994 cnt.restoreLastLayout();
995 // FIXME cnt.restoreLastCounter()?
997 // Record if this inset is embedded in a title layout
998 // This is needed to decide when \maketitle is output.
999 intitle_context_ = it.paragraph().layout().intitle;
1000 // Also check embedding layouts
1001 size_t const n = it.depth();
1002 for (size_t i = 0; i < n; ++i) {
1003 if (it[i].paragraph().layout().intitle) {
1004 intitle_context_ = true;
1009 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1010 // Note that we do not need to call:
1011 // tclass.counters().clearLastLayout()
1012 // since we are saving and restoring the existing counters, etc.
1013 Counters savecnt = tclass.counters();
1014 tclass.counters().reset();
1015 // we need float information even in note insets (#9760)
1016 tclass.counters().current_float(savecnt.current_float());
1017 tclass.counters().isSubfloat(savecnt.isSubfloat());
1018 buffer().updateBuffer(it2, utype, deleted);
1019 tclass.counters() = move(savecnt);
1024 void InsetText::toString(odocstream & os) const
1026 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1030 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1031 bool const shorten) const
1033 if (!getLayout().isInToc())
1035 text().forOutliner(os, maxlen, shorten);
1039 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1040 UpdateType utype, TocBackend & backend) const
1042 DocIterator dit = cdit;
1043 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1044 iterateForToc(dit, output_active, utype, backend);
1048 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1049 UpdateType utype, TocBackend & backend) const
1051 DocIterator dit = cdit;
1052 // This also ensures that any document has a table of contents
1053 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1055 BufferParams const & bufparams = buffer_->params();
1056 int const min_toclevel = bufparams.documentClass().min_toclevel();
1057 // we really should have done this before we got here, but it
1058 // can't hurt too much to do it again
1059 bool const doing_output = output_active && producesOutput();
1061 // For each paragraph,
1062 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1063 // paragraphs as needed.
1064 // * Traverse its insets and let them add their toc items
1065 // * Compute the main table of contents (this is hardcoded)
1066 // * Add the list of changes
1067 ParagraphList const & pars = paragraphs();
1068 pit_type pend = paragraphs().size();
1069 // Record pairs {start,end} of where a toc item was opened for a paragraph
1070 // and where it must be closed
1071 stack<pair<pit_type, pit_type>> addtotoc_stack;
1073 for (pit_type pit = 0; pit != pend; ++pit) {
1074 Paragraph const & par = pars[pit];
1078 // Custom AddToToc in paragraph layouts (i.e. theorems)
1079 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1081 openAddToTocForParagraph(pit, dit, output_active, backend);
1082 addtotoc_stack.push({pit, end});
1085 // If we find an InsetArgument that is supposed to provide the TOC caption,
1086 // we'll save it for use later.
1087 InsetArgument const * arginset = nullptr;
1088 for (auto const & table : par.insetList()) {
1089 dit.pos() = table.pos;
1090 table.inset->addToToc(dit, doing_output, utype, backend);
1091 if (InsetArgument const * x = table.inset->asInsetArgument())
1092 if (x->isTocCaption())
1096 // End custom AddToToc in paragraph layouts
1097 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1098 // execute the closing function
1099 closeAddToTocForParagraph(addtotoc_stack.top().first,
1100 addtotoc_stack.top().second, backend);
1101 addtotoc_stack.pop();
1104 // now the toc entry for the paragraph in the main table of contents
1105 int const toclevel = text().getTocLevel(pit);
1106 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1107 // insert this into the table of contents
1108 docstring tocstring;
1109 int const length = (doing_output && utype == OutputUpdate) ?
1110 INT_MAX : TOC_ENTRY_LENGTH;
1112 tocstring = par.labelString();
1113 if (!tocstring.empty())
1115 arginset->text().forOutliner(tocstring, length);
1117 par.forOutliner(tocstring, length);
1119 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1120 tocstring, doing_output));
1123 // And now the list of changes.
1124 par.addChangesToToc(dit, buffer(), doing_output, backend);
1129 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1130 DocIterator const & dit,
1132 TocBackend & backend) const
1134 Paragraph const & par = paragraphs()[pit];
1135 TocBuilder & b = backend.builder(par.layout().tocType());
1136 docstring const & label = par.labelString();
1137 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1138 return text().lastInSequence(pit);
1142 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1143 TocBackend & backend) const
1145 Paragraph const & par = paragraphs()[start];
1146 TocBuilder & b = backend.builder(par.layout().tocType());
1147 if (par.layout().isTocCaption()) {
1149 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1150 b.argumentItem(str);
1156 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1158 if (buffer().isClean())
1159 return Inset::notifyCursorLeaves(old, cur);
1161 // find text inset in old cursor
1162 Cursor insetCur = old;
1163 int scriptSlice = insetCur.find(this);
1164 // we can try to continue here. returning true means
1165 // the cursor is "now" invalid. which it was.
1166 LASSERT(scriptSlice != -1, return true);
1167 insetCur.cutOff(scriptSlice);
1168 LASSERT(&insetCur.inset() == this, return true);
1170 // update the old paragraph's words
1171 insetCur.paragraph().updateWords();
1173 return Inset::notifyCursorLeaves(old, cur);
1177 bool InsetText::completionSupported(Cursor const & cur) const
1179 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1180 return text_.completionSupported(cur);
1184 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1186 return completionSupported(cur);
1190 bool InsetText::automaticInlineCompletion() const
1192 return lyxrc.completion_inline_text;
1196 bool InsetText::automaticPopupCompletion() const
1198 return lyxrc.completion_popup_text;
1202 bool InsetText::showCompletionCursor() const
1204 return lyxrc.completion_cursor_text &&
1205 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1209 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1211 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1215 docstring InsetText::completionPrefix(Cursor const & cur) const
1217 if (!completionSupported(cur))
1219 return text_.completionPrefix(cur);
1223 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1226 if (!completionSupported(cur))
1229 return text_.insertCompletion(cur, s, finished);
1233 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1234 Dimension & dim) const
1236 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1237 tm.completionPosAndDim(cur, x, y, dim);
1241 string InsetText::contextMenu(BufferView const &, int, int) const
1243 string context_menu = contextMenuName();
1244 if (context_menu != InsetText::contextMenuName())
1245 context_menu += ";" + InsetText::contextMenuName();
1246 return context_menu;
1250 string InsetText::contextMenuName() const
1252 return "context-edit";
1256 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1258 OutputParams rp(&buffer().params().encoding());
1259 rp.for_tooltip = true;
1260 odocstringstream oss;
1263 ParagraphList::const_iterator beg = paragraphs().begin();
1264 ParagraphList::const_iterator end = paragraphs().end();
1265 ParagraphList::const_iterator it = beg;
1266 bool ref_printed = false;
1268 for (; it != end; ++it) {
1271 if ((*it).isRTL(buffer().params()))
1272 oss << "<div dir=\"rtl\">";
1273 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1274 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1277 docstring str = oss.str();
1279 str += from_ascii("\n\n") + _("[contains tracked changes]");
1280 support::truncateWithEllipsis(str, len);
1285 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1287 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1291 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1293 // Nested cprotect content needs \cprotect
1295 if (producesOutput() && hasCProtectContent(fragile))
1298 // Environments generally need cprotection in fragile context
1299 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1302 if (!getLayout().needsCProtect())
1305 // Environments and "no latex" types (e.g., knitr chunks)
1306 // need cprotection regardless the content
1307 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1310 // If the inset does not produce output (e.g. Note or Branch),
1311 // we can ignore the contained paragraphs
1312 if (!producesOutput())
1315 // Commands need cprotection if they contain specific chars
1316 int const nchars_escape = 9;
1317 static char_type const chars_escape[nchars_escape] = {
1318 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1320 ParagraphList const & pars = paragraphs();
1321 pit_type pend = pit_type(paragraphs().size());
1323 for (pit_type pit = 0; pit != pend; ++pit) {
1324 Paragraph const & par = pars[size_type(pit)];
1325 if (par.needsCProtection(fragile))
1327 docstring const par_str = par.asString();
1328 for (int k = 0; k < nchars_escape; k++) {
1329 if (contains(par_str, chars_escape[k]))