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 // 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_SPLIT:
356 case LFUN_INSET_DISSOLVE: {
357 bool const main_inset = text_.isMainText();
358 bool const target_inset = cmd.argument().empty()
359 || cmd.getArg(0) == insetName(lyxCode());
362 status.setEnabled(!main_inset);
366 case LFUN_ARGUMENT_INSERT: {
367 string const arg = cmd.getArg(0);
369 status.setEnabled(false);
372 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
373 return text_.getStatus(cur, cmd, status);
375 Layout::LaTeXArgMap args = getLayout().args();
376 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
377 if (lait != args.end()) {
378 status.setEnabled(true);
379 for (Paragraph const & par : paragraphs())
380 for (auto const & table : par.insetList())
381 if (InsetArgument const * ins = table.inset->asInsetArgument())
382 if (ins->name() == arg) {
383 // we have this already
384 status.setEnabled(false);
388 status.setEnabled(false);
393 // Dispatch only to text_ if the cursor is inside
394 // the text_. It is not for context menus (bug 5797).
396 if (cur.text() == &text_)
397 ret = text_.getStatus(cur, cmd, status);
400 ret = Inset::getStatus(cur, cmd, status);
406 void InsetText::fixParagraphsFont()
408 Font font(inherit_font, buffer().params().language);
409 font.setLanguage(latex_language);
410 ParagraphList::iterator par = paragraphs().begin();
411 ParagraphList::iterator const end = paragraphs().end();
413 if (par->isPassThru())
414 par->resetFonts(font);
415 if (!par->allowParagraphCustomization())
416 par->params().clear();
422 // bool InsetText::isChanged() const
424 // ParagraphList::const_iterator pit = paragraphs().begin();
425 // ParagraphList::const_iterator end = paragraphs().end();
426 // for (; pit != end; ++pit) {
427 // if (pit->isChanged())
434 void InsetText::setChange(Change const & change)
436 ParagraphList::iterator pit = paragraphs().begin();
437 ParagraphList::iterator end = paragraphs().end();
438 for (; pit != end; ++pit) {
439 pit->setChange(change);
444 void InsetText::acceptChanges()
446 text_.acceptChanges();
450 void InsetText::rejectChanges()
452 text_.rejectChanges();
456 void InsetText::validate(LaTeXFeatures & features) const
458 features.useInsetLayout(getLayout());
459 for (Paragraph const & p : paragraphs())
460 p.validate(features);
464 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
466 // This implements the standard way of handling the LaTeX
467 // output of a text inset, either a command or an
468 // environment. Standard collapsible insets should not
469 // redefine this, non-standard ones may call this.
470 InsetLayout const & il = getLayout();
471 if (il.forceOwnlines())
473 bool needendgroup = false;
474 if (!il.latexname().empty()) {
475 if (il.latextype() == InsetLaTeXType::COMMAND) {
477 // FIXME \protect should only be used for fragile
478 // commands, but we do not provide this information yet.
479 if (hasCProtectContent(runparams.moving_arg)) {
480 if (contains(runparams.active_chars, '^')) {
481 // cprotect relies on ^ being on catcode 7
482 os << "\\begingroup\\catcode`\\^=7";
486 } else if (runparams.moving_arg)
488 os << '\\' << from_utf8(il.latexname());
489 if (!il.latexargs().empty())
490 getArgs(os, runparams);
491 if (!il.latexparam().empty())
492 os << from_utf8(il.latexparam());
494 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
499 if (runparams.lastid != -1)
500 os.texrow().start(runparams.lastid,
502 os << "\\begin{" << from_utf8(il.latexname()) << "}";
503 if (!il.latexargs().empty())
504 getArgs(os, runparams);
505 if (!il.latexparam().empty())
506 os << from_utf8(il.latexparam());
510 if (!il.latexargs().empty())
511 getArgs(os, runparams);
512 if (!il.latexparam().empty())
513 os << from_utf8(il.latexparam());
516 if (!il.leftdelim().empty())
517 os << il.leftdelim();
519 OutputParams rp = runparams;
522 if (il.isNeedProtect())
523 rp.moving_arg = true;
524 if (il.isNeedMBoxProtect())
526 if (!il.passThruChars().empty())
527 rp.pass_thru_chars += il.passThruChars();
528 if (!il.newlineCmd().empty())
529 rp.newlinecmd = il.newlineCmd();
531 rp.par_end = paragraphs().size();
533 // Output the contents of the inset
534 latexParagraphs(buffer(), text_, os, rp);
535 runparams.encoding = rp.encoding;
536 // Pass the post_macros upstream
537 runparams.post_macro = rp.post_macro;
538 // These need to be passed upstream as well
539 runparams.need_maketitle = rp.need_maketitle;
540 runparams.have_maketitle = rp.have_maketitle;
542 if (!il.rightdelim().empty())
543 os << il.rightdelim();
545 if (!il.latexname().empty()) {
546 if (il.latextype() == InsetLaTeXType::COMMAND) {
548 if (!il.postcommandargs().empty())
549 getArgs(os, runparams, true);
552 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
553 // A comment environment doesn't need a % before \n\end
554 if (il.isDisplay() || runparams.inComment)
558 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
560 os.protectSpace(true);
563 if (il.forceOwnlines())
568 int InsetText::plaintext(odocstringstream & os,
569 OutputParams const & runparams, size_t max_length) const
571 ParagraphList::const_iterator beg = paragraphs().begin();
572 ParagraphList::const_iterator end = paragraphs().end();
573 ParagraphList::const_iterator it = beg;
574 bool ref_printed = false;
576 for (; it != end; ++it) {
579 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
582 odocstringstream oss;
583 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
584 docstring const str = oss.str();
586 // FIXME: len is not computed fully correctly; in principle,
587 // we have to count the characters after the last '\n'
589 if (os.str().size() >= max_length)
598 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
600 docbook(xs, rp, WriteEverything);
604 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
606 // we will always want to output all our paragraphs when we are
608 OutputParams runparams = rp;
609 runparams.par_begin = 0;
610 runparams.par_end = text().paragraphs().size();
613 xs.startDivision(false);
614 docbookParagraphs(text_, buffer(), xs, runparams);
619 InsetLayout const & il = getLayout();
621 // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
622 // else, typically outside the current paragraph).
623 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
626 // In some cases, the input parameters must be overridden for outer tags.
627 bool writeOuterTag = opts & WriteOuterTag;
629 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
630 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
631 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
632 auto parSize = (size_t) par.size();
633 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
635 writeOuterTag = !allBibitems;
638 // Detect arguments that should be output before/after the paragraph.
639 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
640 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
641 std::set<InsetArgument const *> prependedArguments;
642 for (auto const & par : paragraphs()) {
643 for (pos_type i = 0; i < par.size(); ++i) {
644 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
645 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
646 if (arg->docbookargumentbeforemaintag())
647 prependedArguments.insert(par.getInset(i)->asInsetArgument());
652 std::set<InsetArgument const *> appendedArguments;
653 for (auto const & par : paragraphs()) {
654 for (pos_type i = 0; i < par.size(); ++i) {
655 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
656 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
657 if (arg->docbookargumentaftermaintag())
658 appendedArguments.insert(par.getInset(i)->asInsetArgument());
663 // Start outputting this inset.
664 // - First, wrapper around the inset and its main tag.
666 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
667 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
669 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
670 docstring attrs = docstring();
671 if (!il.docbookattr().empty())
672 attrs += from_ascii(il.docbookattr());
673 if (il.docbooktag() == "link")
674 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
675 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
679 // - Think about the arguments before the paragraph.
680 OutputParams np = runparams;
681 np.docbook_in_par = true;
682 for (auto const & arg : prependedArguments)
683 arg->docbook(xs, np);
685 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
686 runparams.docbook_prepended_arguments = std::move(prependedArguments);
687 runparams.docbook_appended_arguments = appendedArguments;
689 // - Deal with the first item.
690 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
692 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
693 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
695 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
696 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
699 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
701 // With respect to XHTML, paragraphs are still allowed here.
702 if (!allowMultiPar())
703 runparams.docbook_make_pars = false;
705 runparams.pass_thru = true;
707 // - Write the main content of the inset.
708 xs.startDivision(false);
709 docbookParagraphs(text_, buffer(), xs, runparams);
712 // - Think about the arguments after the paragraph.
713 for (auto const & arg : appendedArguments)
714 arg->docbook(xs, np);
716 // - Close the required tags.
718 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
719 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
721 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
722 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
724 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
725 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
727 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
728 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
733 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
735 return insetAsXHTML(xs, runparams, WriteEverything);
740 // There are cases where we may need to close open fonts and such
741 // and then re-open them when we are done. This would be the case, e.g.,
742 // if we were otherwise about to write:
743 // <em>word <div class='foot'>footnote text.</div> emph</em>
744 // The problem isn't so much that the footnote text will get emphasized:
745 // we can handle that with CSS. The problem is that this is invalid XHTML.
746 // One solution would be to make the footnote <span>, but the problem is
747 // completely general, and so we'd have to make absolutely everything into
748 // span. What I think will work is to check if we're about to write "div" and,
749 // if so, try to close fonts, etc.
750 // There are probably limits to how well we can do here, though, and we will
751 // have to rely upon users not putting footnotes inside noun-type insets.
752 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
753 XHTMLOptions opts) const
755 // we will always want to output all our paragraphs when we are
757 OutputParams runparams = rp;
758 runparams.par_begin = 0;
759 runparams.par_end = text().paragraphs().size();
762 xs.startDivision(false);
763 xhtmlParagraphs(text_, buffer(), xs, runparams);
768 InsetLayout const & il = getLayout();
769 if (opts & WriteOuterTag)
770 xs << xml::StartTag(il.htmltag(), il.htmlattr());
772 if ((opts & WriteLabel) && !il.counter().empty()) {
773 BufferParams const & bp = buffer().masterBuffer()->params();
774 Counters & cntrs = bp.documentClass().counters();
775 cntrs.step(il.counter(), OutputUpdate);
776 // FIXME: translate to paragraph language
777 if (!il.htmllabel().empty()) {
778 docstring const lbl =
779 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
780 // FIXME is this check necessary?
782 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
784 xs << xml::EndTag(il.htmllabeltag());
789 if (opts & WriteInnerTag)
790 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
792 // we will eventually lose information about the containing inset
793 if (!allowMultiPar() || opts == JustText)
794 runparams.html_make_pars = false;
796 runparams.pass_thru = true;
798 xs.startDivision(false);
799 xhtmlParagraphs(text_, buffer(), xs, runparams);
802 if (opts & WriteInnerTag)
803 xs << xml::EndTag(il.htmlinnertag());
805 if (opts & WriteOuterTag)
806 xs << xml::EndTag(il.htmltag());
812 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
813 bool const post) const
815 OutputParams runparams = runparams_in;
816 runparams.local_font =
817 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
819 runparams.pass_thru = true;
821 latexArgInsetsForParent(paragraphs(), os, runparams,
822 getLayout().postcommandargs(), "post:");
824 latexArgInsetsForParent(paragraphs(), os, runparams,
825 getLayout().latexargs());
829 void InsetText::cursorPos(BufferView const & bv,
830 CursorSlice const & sl, bool boundary, int & x, int & y) const
832 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
833 y = bv.textMetrics(&text_).cursorY(sl, boundary);
837 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
840 Paragraph & first = paragraphs().front();
841 for (unsigned int i = 0; i < data.length(); ++i)
842 first.insertChar(i, data[i], font, trackChanges);
846 void InsetText::setDrawFrame(bool flag)
852 ColorCode InsetText::frameColor() const
858 void InsetText::setFrameColor(ColorCode col)
864 void InsetText::appendParagraphs(ParagraphList & plist)
866 // There is little we can do here to keep track of changes.
867 // As of 2006/10/20, appendParagraphs is used exclusively by
868 // LyXTabular::setMultiColumn. In this context, the paragraph break
869 // is lost irreversibly and the appended text doesn't really change
871 ParagraphList & pl = paragraphs();
873 ParagraphList::iterator pit = plist.begin();
874 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
876 mergeParagraph(buffer().params(), pl,
877 distance(pl.begin(), ins) - 1);
879 ParagraphList::iterator const pend = plist.end();
880 for (; pit != pend; ++pit)
885 void InsetText::addPreview(DocIterator const & text_inset_pos,
886 PreviewLoader & loader) const
888 ParagraphList::const_iterator pit = paragraphs().begin();
889 ParagraphList::const_iterator pend = paragraphs().end();
892 DocIterator inset_pos = text_inset_pos;
893 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
895 for (; pit != pend; ++pit, ++pidx) {
896 InsetList::const_iterator it = pit->insetList().begin();
897 InsetList::const_iterator end = pit->insetList().end();
898 inset_pos.pit() = pidx;
899 for (; it != end; ++it) {
900 inset_pos.pos() = it->pos;
901 it->inset->addPreview(inset_pos, loader);
907 ParagraphList const & InsetText::paragraphs() const
909 return text_.paragraphs();
913 ParagraphList & InsetText::paragraphs()
915 return text_.paragraphs();
919 bool InsetText::hasCProtectContent(bool fragile) const
921 fragile |= getLayout().isNeedProtect();
922 ParagraphList const & pars = paragraphs();
923 pit_type pend = pit_type(paragraphs().size());
924 for (pit_type pit = 0; pit != pend; ++pit) {
925 Paragraph const & par = pars[size_type(pit)];
926 if (par.needsCProtection(fragile))
933 bool InsetText::insetAllowed(InsetCode code) const
936 // Arguments and (plain) quotes are also allowed in PassThru insets
941 return !isPassThru();
946 bool InsetText::allowSpellCheck() const
948 return getLayout().spellcheck() && !getLayout().isPassThru();
952 bool InsetText::allowMultiPar() const
954 return getLayout().isMultiPar();
958 bool InsetText::forcePlainLayout(idx_type) const
960 return getLayout().forcePlainLayout();
964 bool InsetText::allowParagraphCustomization(idx_type) const
966 return getLayout().allowParagraphCustomization();
970 bool InsetText::forceLocalFontSwitch() const
972 return getLayout().forceLocalFontSwitch();
976 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
978 ParIterator it2 = it;
980 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
981 if (producesOutput()) {
982 InsetLayout const & il = getLayout();
983 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
984 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
986 // LYXERR0("Entering " << name());
987 cnt.clearLastLayout();
988 // FIXME cnt.saveLastCounter()?
990 buffer().updateBuffer(it2, utype, deleted);
992 // LYXERR0("Exiting " << name());
993 cnt.restoreLastLayout();
994 // FIXME cnt.restoreLastCounter()?
996 // Record if this inset is embedded in a title layout
997 // This is needed to decide when \maketitle is output.
998 intitle_context_ = it.paragraph().layout().intitle;
999 // Also check embedding layouts
1000 size_t const n = it.depth();
1001 for (size_t i = 0; i < n; ++i) {
1002 if (it[i].paragraph().layout().intitle) {
1003 intitle_context_ = true;
1008 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1009 // Note that we do not need to call:
1010 // tclass.counters().clearLastLayout()
1011 // since we are saving and restoring the existing counters, etc.
1012 Counters savecnt = tclass.counters();
1013 tclass.counters().reset();
1014 // we need float information even in note insets (#9760)
1015 tclass.counters().current_float(savecnt.current_float());
1016 tclass.counters().isSubfloat(savecnt.isSubfloat());
1017 buffer().updateBuffer(it2, utype, deleted);
1018 tclass.counters() = move(savecnt);
1023 void InsetText::toString(odocstream & os) const
1025 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1029 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1030 bool const shorten) const
1032 if (!getLayout().isInToc())
1034 text().forOutliner(os, maxlen, shorten);
1038 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1039 UpdateType utype, TocBackend & backend) const
1041 DocIterator dit = cdit;
1042 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1043 iterateForToc(dit, output_active, utype, backend);
1047 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1048 UpdateType utype, TocBackend & backend) const
1050 DocIterator dit = cdit;
1051 // This also ensures that any document has a table of contents
1052 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1054 BufferParams const & bufparams = buffer_->params();
1055 int const min_toclevel = bufparams.documentClass().min_toclevel();
1056 // we really should have done this before we got here, but it
1057 // can't hurt too much to do it again
1058 bool const doing_output = output_active && producesOutput();
1060 // For each paragraph,
1061 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1062 // paragraphs as needed.
1063 // * Traverse its insets and let them add their toc items
1064 // * Compute the main table of contents (this is hardcoded)
1065 // * Add the list of changes
1066 ParagraphList const & pars = paragraphs();
1067 pit_type pend = paragraphs().size();
1068 // Record pairs {start,end} of where a toc item was opened for a paragraph
1069 // and where it must be closed
1070 stack<pair<pit_type, pit_type>> addtotoc_stack;
1072 for (pit_type pit = 0; pit != pend; ++pit) {
1073 Paragraph const & par = pars[pit];
1077 // Custom AddToToc in paragraph layouts (i.e. theorems)
1078 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1080 openAddToTocForParagraph(pit, dit, output_active, backend);
1081 addtotoc_stack.push({pit, end});
1084 // If we find an InsetArgument that is supposed to provide the TOC caption,
1085 // we'll save it for use later.
1086 InsetArgument const * arginset = nullptr;
1087 for (auto const & table : par.insetList()) {
1088 dit.pos() = table.pos;
1089 table.inset->addToToc(dit, doing_output, utype, backend);
1090 if (InsetArgument const * x = table.inset->asInsetArgument())
1091 if (x->isTocCaption())
1095 // End custom AddToToc in paragraph layouts
1096 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1097 // execute the closing function
1098 closeAddToTocForParagraph(addtotoc_stack.top().first,
1099 addtotoc_stack.top().second, backend);
1100 addtotoc_stack.pop();
1103 // now the toc entry for the paragraph in the main table of contents
1104 int const toclevel = text().getTocLevel(pit);
1105 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1106 // insert this into the table of contents
1107 docstring tocstring;
1108 int const length = (doing_output && utype == OutputUpdate) ?
1109 INT_MAX : TOC_ENTRY_LENGTH;
1111 tocstring = par.labelString();
1112 if (!tocstring.empty())
1114 arginset->text().forOutliner(tocstring, length);
1116 par.forOutliner(tocstring, length);
1118 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1119 tocstring, doing_output));
1122 // And now the list of changes.
1123 par.addChangesToToc(dit, buffer(), doing_output, backend);
1128 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1129 DocIterator const & dit,
1131 TocBackend & backend) const
1133 Paragraph const & par = paragraphs()[pit];
1134 TocBuilder & b = backend.builder(par.layout().tocType());
1135 docstring const & label = par.labelString();
1136 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1137 return text().lastInSequence(pit);
1141 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1142 TocBackend & backend) const
1144 Paragraph const & par = paragraphs()[start];
1145 TocBuilder & b = backend.builder(par.layout().tocType());
1146 if (par.layout().isTocCaption()) {
1148 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1149 b.argumentItem(str);
1155 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1157 if (buffer().isClean())
1158 return Inset::notifyCursorLeaves(old, cur);
1160 // find text inset in old cursor
1161 Cursor insetCur = old;
1162 int scriptSlice = insetCur.find(this);
1163 // we can try to continue here. returning true means
1164 // the cursor is "now" invalid. which it was.
1165 LASSERT(scriptSlice != -1, return true);
1166 insetCur.cutOff(scriptSlice);
1167 LASSERT(&insetCur.inset() == this, return true);
1169 // update the old paragraph's words
1170 insetCur.paragraph().updateWords();
1172 return Inset::notifyCursorLeaves(old, cur);
1176 bool InsetText::completionSupported(Cursor const & cur) const
1178 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1179 return text_.completionSupported(cur);
1183 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1185 return completionSupported(cur);
1189 bool InsetText::automaticInlineCompletion() const
1191 return lyxrc.completion_inline_text;
1195 bool InsetText::automaticPopupCompletion() const
1197 return lyxrc.completion_popup_text;
1201 bool InsetText::showCompletionCursor() const
1203 return lyxrc.completion_cursor_text &&
1204 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1208 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1210 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1214 docstring InsetText::completionPrefix(Cursor const & cur) const
1216 if (!completionSupported(cur))
1218 return text_.completionPrefix(cur);
1222 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1225 if (!completionSupported(cur))
1228 return text_.insertCompletion(cur, s, finished);
1232 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1233 Dimension & dim) const
1235 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1236 tm.completionPosAndDim(cur, x, y, dim);
1240 string InsetText::contextMenu(BufferView const &, int, int) const
1242 string context_menu = contextMenuName();
1243 if (context_menu != InsetText::contextMenuName())
1244 context_menu += ";" + InsetText::contextMenuName();
1245 return context_menu;
1249 string InsetText::contextMenuName() const
1251 return "context-edit";
1255 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1257 OutputParams rp(&buffer().params().encoding());
1258 rp.for_tooltip = true;
1259 odocstringstream oss;
1262 ParagraphList::const_iterator beg = paragraphs().begin();
1263 ParagraphList::const_iterator end = paragraphs().end();
1264 ParagraphList::const_iterator it = beg;
1265 bool ref_printed = false;
1267 for (; it != end; ++it) {
1270 if ((*it).isRTL(buffer().params()))
1271 oss << "<div dir=\"rtl\">";
1272 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1273 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1276 docstring str = oss.str();
1278 str += from_ascii("\n\n") + _("[contains tracked changes]");
1279 support::truncateWithEllipsis(str, len);
1284 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1286 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1290 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1292 // Nested cprotect content needs \cprotect
1294 if (producesOutput() && hasCProtectContent(fragile))
1297 // Environments generally need cprotection in fragile context
1298 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1301 if (!getLayout().needsCProtect())
1304 // Environments and "no latex" types (e.g., knitr chunks)
1305 // need cprotection regardless the content
1306 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1309 // If the inset does not produce output (e.g. Note or Branch),
1310 // we can ignore the contained paragraphs
1311 if (!producesOutput())
1314 // Commands need cprotection if they contain specific chars
1315 int const nchars_escape = 9;
1316 static char_type const chars_escape[nchars_escape] = {
1317 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1319 ParagraphList const & pars = paragraphs();
1320 pit_type pend = pit_type(paragraphs().size());
1322 for (pit_type pit = 0; pit != pend; ++pit) {
1323 Paragraph const & par = pars[size_type(pit)];
1324 if (par.needsCProtection(fragile))
1326 docstring const par_str = par.asString();
1327 for (int k = 0; k < nchars_escape; k++) {
1328 if (contains(par_str, chars_escape[k]))