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::setOuterFont(BufferView & bv, FontInfo const & outer) const
189 TextMetrics & tm = bv.textMetrics(&text_);
190 FontInfo tmpfont = getFont();
191 tmpfont.realize(outer);
192 tm.font_.fontInfo() = tmpfont;
196 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
198 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
200 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
202 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
203 mi.base.textwidth -= horiz_offset;
205 // Remember the full outer font
206 setOuterFont(*mi.base.bv, mi.base.font);
207 // and use it in these metrics computation.
208 mi.base.font = tm.font_.fontInfo();
210 // This can happen when a layout has a left and right margin,
211 // and the view is made very narrow. We can't do better than
212 // to draw it partly out of view (bug 5890).
213 if (mi.base.textwidth < 1)
214 mi.base.textwidth = 1;
217 tm.metrics(mi, dim, mi.base.textwidth);
220 mi.base.textwidth += horiz_offset;
221 dim.asc += topOffset(mi.base.bv);
222 dim.des += bottomOffset(mi.base.bv);
223 dim.wid += horiz_offset;
227 void InsetText::draw(PainterInfo & pi, int x, int y) const
229 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
231 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
232 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
233 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
234 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
235 int const xframe = x + leftOffset(pi.base.bv) / 2;
236 bool change_drawn = false;
238 pi.pain.fillRectangle(xframe, yframe, w, h,
239 pi.backgroundColor(this));
242 Changer dummy = changeVar(pi.background_color,
243 pi.backgroundColor(this, false));
244 // The change tracking cue must not be inherited
245 Changer dummy2 = changeVar(pi.change, Change());
246 tm.draw(pi, x + leftOffset(pi.base.bv), y);
250 // Change color of the frame in tracked changes, like for tabulars.
251 // Only do so if the color is not custom. But do so even if RowPainter
252 // handles the strike-through already.
254 if (pi.change.changed()
255 // Originally, these are the colors with role Text, from role() in
256 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
257 // types, and also maybe it need not match in the future.
258 && (frameColor() == Color_foreground
259 || frameColor() == Color_cursor
260 || frameColor() == Color_preview
261 || frameColor() == Color_tabularline
262 || frameColor() == Color_previewframe)) {
263 c = pi.change.color();
267 pi.pain.rectangle(xframe, yframe, w, h, c);
270 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
271 // Do not draw the change tracking cue if already done by RowPainter and
272 // do not draw the cue for INSERTED if the information is already in the
273 // color of the frame
274 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
278 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
280 pit_type const pit = front ? 0 : paragraphs().size() - 1;
281 pos_type pos = front ? 0 : paragraphs().back().size();
283 // if visual information is not to be ignored, move to extreme right/left
284 if (entry_from != ENTRY_DIRECTION_IGNORE) {
285 Cursor temp_cur = cur;
286 temp_cur.pit() = pit;
287 temp_cur.pos() = pos;
288 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
289 pos = temp_cur.pos();
292 cur.top().setPitPos(pit, pos);
293 cur.setCurrentFont();
298 Inset * InsetText::editXY(Cursor & cur, int x, int y)
300 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
304 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
306 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
309 // See bug #9042, for instance.
311 // Force any new text to latex_language FIXME: This
312 // should only be necessary in constructor, but new
313 // paragraphs that are created by pressing enter at
314 // the start of an existing paragraph get the buffer
315 // language and not latex_language, so we take this
316 // brute force approach.
317 cur.current_font.setLanguage(latex_language);
318 cur.real_current_font.setLanguage(latex_language);
322 switch (cmd.action()) {
324 case LFUN_CLIPBOARD_PASTE:
325 case LFUN_SELECTION_PASTE:
326 case LFUN_PRIMARY_SELECTION_PASTE:
327 text_.dispatch(cur, cmd);
328 // If we we can only store plain text, we must reset all
330 // FIXME: Change only the pasted paragraphs
334 case LFUN_INSET_SPLIT:
335 case LFUN_INSET_DISSOLVE: {
336 bool const main_inset = text_.isMainText();
337 bool const target_inset = cmd.argument().empty()
338 || cmd.getArg(0) == insetName(lyxCode());
340 if (!main_inset && target_inset) {
341 UndoGroupHelper ugh(&buffer());
342 // Text::dissolveInset assumes that the cursor
343 // is inside the Inset.
344 if (&cur.inset() != this) {
346 cur.pushBackward(*this);
348 text_.dispatch(cur, cmd);
355 text_.dispatch(cur, cmd);
358 if (!cur.result().dispatched())
359 Inset::doDispatch(cur, cmd);
363 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
364 FuncStatus & status) const
366 switch (cmd.action()) {
367 case LFUN_INSET_SPLIT:
368 case LFUN_INSET_DISSOLVE: {
369 bool const main_inset = text_.isMainText();
370 bool const target_inset = cmd.argument().empty()
371 || cmd.getArg(0) == insetName(lyxCode());
374 status.setEnabled(!main_inset);
378 case LFUN_ARGUMENT_INSERT: {
379 string const arg = cmd.getArg(0);
381 status.setEnabled(false);
384 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
385 return text_.getStatus(cur, cmd, status);
387 Layout::LaTeXArgMap args = getLayout().args();
388 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
389 if (lait != args.end()) {
390 status.setEnabled(true);
391 for (Paragraph const & par : paragraphs())
392 for (auto const & table : par.insetList())
393 if (InsetArgument const * ins = table.inset->asInsetArgument())
394 if (ins->name() == arg) {
395 // we have this already
396 status.setEnabled(false);
400 status.setEnabled(false);
405 // Dispatch only to text_ if the cursor is inside
406 // the text_. It is not for context menus (bug 5797).
408 if (cur.text() == &text_)
409 ret = text_.getStatus(cur, cmd, status);
412 ret = Inset::getStatus(cur, cmd, status);
418 void InsetText::fixParagraphsFont()
420 Font font(inherit_font, buffer().params().language);
421 font.setLanguage(latex_language);
422 ParagraphList::iterator par = paragraphs().begin();
423 ParagraphList::iterator const end = paragraphs().end();
425 if (par->isPassThru())
426 par->resetFonts(font);
427 if (!par->allowParagraphCustomization())
428 par->params().clear();
434 // bool InsetText::isChanged() const
436 // ParagraphList::const_iterator pit = paragraphs().begin();
437 // ParagraphList::const_iterator end = paragraphs().end();
438 // for (; pit != end; ++pit) {
439 // if (pit->isChanged())
446 void InsetText::setChange(Change const & change)
448 ParagraphList::iterator pit = paragraphs().begin();
449 ParagraphList::iterator end = paragraphs().end();
450 for (; pit != end; ++pit) {
451 pit->setChange(change);
456 void InsetText::acceptChanges()
458 text_.acceptChanges();
462 void InsetText::rejectChanges()
464 text_.rejectChanges();
468 void InsetText::validate(LaTeXFeatures & features) const
470 features.useInsetLayout(getLayout());
471 for (Paragraph const & p : paragraphs())
472 p.validate(features);
476 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
478 // This implements the standard way of handling the LaTeX
479 // output of a text inset, either a command or an
480 // environment. Standard collapsible insets should not
481 // redefine this, non-standard ones may call this.
482 InsetLayout const & il = getLayout();
483 if (il.forceOwnlines())
485 bool needendgroup = false;
486 if (!il.latexname().empty()) {
487 if (il.latextype() == InsetLaTeXType::COMMAND) {
489 // FIXME \protect should only be used for fragile
490 // commands, but we do not provide this information yet.
491 if (hasCProtectContent(runparams.moving_arg)) {
492 if (contains(runparams.active_chars, '^')) {
493 // cprotect relies on ^ being on catcode 7
494 os << "\\begingroup\\catcode`\\^=7";
498 } else if (runparams.moving_arg)
500 os << '\\' << from_utf8(il.latexname());
501 if (!il.latexargs().empty())
502 getArgs(os, runparams);
503 if (!il.latexparam().empty())
504 os << from_utf8(il.latexparam());
506 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
511 if (runparams.lastid != -1)
512 os.texrow().start(runparams.lastid,
514 os << "\\begin{" << from_utf8(il.latexname()) << "}";
515 if (!il.latexargs().empty())
516 getArgs(os, runparams);
517 if (!il.latexparam().empty())
518 os << from_utf8(il.latexparam());
522 if (!il.latexargs().empty())
523 getArgs(os, runparams);
524 if (!il.latexparam().empty())
525 os << from_utf8(il.latexparam());
528 if (!il.leftdelim().empty())
529 os << il.leftdelim();
531 OutputParams rp = runparams;
534 if (il.isNeedProtect())
535 rp.moving_arg = true;
536 if (il.isNeedMBoxProtect())
538 if (!il.passThruChars().empty())
539 rp.pass_thru_chars += il.passThruChars();
540 if (!il.newlineCmd().empty())
541 rp.newlinecmd = il.newlineCmd();
543 rp.par_end = paragraphs().size();
545 // Output the contents of the inset
546 latexParagraphs(buffer(), text_, os, rp);
547 runparams.encoding = rp.encoding;
548 // Pass the post_macros upstream
549 runparams.post_macro = rp.post_macro;
550 // These need to be passed upstream as well
551 runparams.need_maketitle = rp.need_maketitle;
552 runparams.have_maketitle = rp.have_maketitle;
554 if (!il.rightdelim().empty())
555 os << il.rightdelim();
557 if (!il.latexname().empty()) {
558 if (il.latextype() == InsetLaTeXType::COMMAND) {
560 if (!il.postcommandargs().empty())
561 getArgs(os, runparams, true);
564 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
565 // A comment environment doesn't need a % before \n\end
566 if (il.isDisplay() || runparams.inComment)
570 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
572 os.protectSpace(true);
575 if (il.forceOwnlines())
580 int InsetText::plaintext(odocstringstream & os,
581 OutputParams const & runparams, size_t max_length) const
583 ParagraphList::const_iterator beg = paragraphs().begin();
584 ParagraphList::const_iterator end = paragraphs().end();
585 ParagraphList::const_iterator it = beg;
586 bool ref_printed = false;
588 for (; it != end; ++it) {
591 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
594 odocstringstream oss;
595 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
596 docstring const str = oss.str();
598 // FIXME: len is not computed fully correctly; in principle,
599 // we have to count the characters after the last '\n'
601 if (os.str().size() >= max_length)
610 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
612 docbook(xs, rp, WriteEverything);
616 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
618 // we will always want to output all our paragraphs when we are
620 OutputParams runparams = rp;
621 runparams.par_begin = 0;
622 runparams.par_end = text().paragraphs().size();
625 xs.startDivision(false);
626 docbookParagraphs(text_, buffer(), xs, runparams);
631 InsetLayout const & il = getLayout();
633 // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
634 // else, typically outside the current paragraph).
635 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
638 // In some cases, the input parameters must be overridden for outer tags.
639 bool writeOuterTag = opts & WriteOuterTag;
641 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
642 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
643 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
644 auto parSize = (size_t) par.size();
645 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
647 writeOuterTag = !allBibitems;
650 // Detect arguments that should be output before/after the paragraph.
651 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
652 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
653 std::set<InsetArgument const *> prependedArguments;
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->docbookargumentbeforemaintag())
659 prependedArguments.insert(par.getInset(i)->asInsetArgument());
664 std::set<InsetArgument const *> appendedArguments;
665 for (auto const & par : paragraphs()) {
666 for (pos_type i = 0; i < par.size(); ++i) {
667 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
668 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
669 if (arg->docbookargumentaftermaintag())
670 appendedArguments.insert(par.getInset(i)->asInsetArgument());
675 // Start outputting this inset.
676 // - First, wrapper around the inset and its main tag.
678 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
679 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
681 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
682 docstring attrs = docstring();
683 if (!il.docbookattr().empty())
684 attrs += from_ascii(il.docbookattr());
685 if (il.docbooktag() == "link")
686 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
687 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
691 // - Think about the arguments before the paragraph.
692 OutputParams np = runparams;
693 np.docbook_in_par = true;
694 for (auto const & arg : prependedArguments)
695 arg->docbook(xs, np);
697 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
698 runparams.docbook_prepended_arguments = std::move(prependedArguments);
699 runparams.docbook_appended_arguments = appendedArguments;
701 // - Deal with the first item.
702 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
704 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
705 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
707 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
708 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
711 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
713 // With respect to XHTML, paragraphs are still allowed here.
714 if (!allowMultiPar())
715 runparams.docbook_make_pars = false;
717 runparams.pass_thru = true;
719 // - Write the main content of the inset.
720 xs.startDivision(false);
721 docbookParagraphs(text_, buffer(), xs, runparams);
724 // - Think about the arguments after the paragraph.
725 for (auto const & arg : appendedArguments)
726 arg->docbook(xs, np);
728 // - Close the required tags.
730 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
731 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
733 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
734 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
736 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
737 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
739 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
740 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
745 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
747 return insetAsXHTML(xs, runparams, WriteEverything);
752 // There are cases where we may need to close open fonts and such
753 // and then re-open them when we are done. This would be the case, e.g.,
754 // if we were otherwise about to write:
755 // <em>word <div class='foot'>footnote text.</div> emph</em>
756 // The problem isn't so much that the footnote text will get emphasized:
757 // we can handle that with CSS. The problem is that this is invalid XHTML.
758 // One solution would be to make the footnote <span>, but the problem is
759 // completely general, and so we'd have to make absolutely everything into
760 // span. What I think will work is to check if we're about to write "div" and,
761 // if so, try to close fonts, etc.
762 // There are probably limits to how well we can do here, though, and we will
763 // have to rely upon users not putting footnotes inside noun-type insets.
764 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
765 XHTMLOptions opts) const
767 // we will always want to output all our paragraphs when we are
769 OutputParams runparams = rp;
770 runparams.par_begin = 0;
771 runparams.par_end = text().paragraphs().size();
774 xs.startDivision(false);
775 xhtmlParagraphs(text_, buffer(), xs, runparams);
780 InsetLayout const & il = getLayout();
781 if (opts & WriteOuterTag)
782 xs << xml::StartTag(il.htmltag(), il.htmlattr());
784 if ((opts & WriteLabel) && !il.counter().empty()) {
785 BufferParams const & bp = buffer().masterBuffer()->params();
786 Counters & cntrs = bp.documentClass().counters();
787 cntrs.step(il.counter(), OutputUpdate);
788 // FIXME: translate to paragraph language
789 if (!il.htmllabel().empty()) {
790 docstring const lbl =
791 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
792 // FIXME is this check necessary?
794 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
796 xs << xml::EndTag(il.htmllabeltag());
801 if (opts & WriteInnerTag)
802 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
804 // we will eventually lose information about the containing inset
805 if (!allowMultiPar() || opts == JustText)
806 runparams.html_make_pars = false;
808 runparams.pass_thru = true;
810 xs.startDivision(false);
811 xhtmlParagraphs(text_, buffer(), xs, runparams);
814 if (opts & WriteInnerTag)
815 xs << xml::EndTag(il.htmlinnertag());
817 if (opts & WriteOuterTag)
818 xs << xml::EndTag(il.htmltag());
824 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
825 bool const post) const
827 OutputParams runparams = runparams_in;
828 runparams.local_font =
829 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
831 runparams.pass_thru = true;
833 latexArgInsetsForParent(paragraphs(), os, runparams,
834 getLayout().postcommandargs(), "post:");
836 latexArgInsetsForParent(paragraphs(), os, runparams,
837 getLayout().latexargs());
841 void InsetText::cursorPos(BufferView const & bv,
842 CursorSlice const & sl, bool boundary, int & x, int & y) const
844 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
845 y = bv.textMetrics(&text_).cursorY(sl, boundary);
849 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
852 Paragraph & first = paragraphs().front();
853 for (unsigned int i = 0; i < data.length(); ++i)
854 first.insertChar(i, data[i], font, trackChanges);
858 void InsetText::setDrawFrame(bool flag)
864 ColorCode InsetText::frameColor() const
870 void InsetText::setFrameColor(ColorCode col)
876 void InsetText::appendParagraphs(ParagraphList & plist)
878 // There is little we can do here to keep track of changes.
879 // As of 2006/10/20, appendParagraphs is used exclusively by
880 // LyXTabular::setMultiColumn. In this context, the paragraph break
881 // is lost irreversibly and the appended text doesn't really change
883 ParagraphList & pl = paragraphs();
885 ParagraphList::iterator pit = plist.begin();
886 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
888 mergeParagraph(buffer().params(), pl,
889 distance(pl.begin(), ins) - 1);
891 ParagraphList::iterator const pend = plist.end();
892 for (; pit != pend; ++pit)
897 void InsetText::addPreview(DocIterator const & text_inset_pos,
898 PreviewLoader & loader) const
900 ParagraphList::const_iterator pit = paragraphs().begin();
901 ParagraphList::const_iterator pend = paragraphs().end();
904 DocIterator inset_pos = text_inset_pos;
905 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
907 for (; pit != pend; ++pit, ++pidx) {
908 InsetList::const_iterator it = pit->insetList().begin();
909 InsetList::const_iterator end = pit->insetList().end();
910 inset_pos.pit() = pidx;
911 for (; it != end; ++it) {
912 inset_pos.pos() = it->pos;
913 it->inset->addPreview(inset_pos, loader);
919 ParagraphList const & InsetText::paragraphs() const
921 return text_.paragraphs();
925 ParagraphList & InsetText::paragraphs()
927 return text_.paragraphs();
931 bool InsetText::hasCProtectContent(bool fragile) const
933 fragile |= getLayout().isNeedProtect();
934 ParagraphList const & pars = paragraphs();
935 pit_type pend = pit_type(paragraphs().size());
936 for (pit_type pit = 0; pit != pend; ++pit) {
937 Paragraph const & par = pars[size_type(pit)];
938 if (par.needsCProtection(fragile))
945 bool InsetText::insetAllowed(InsetCode code) const
948 // Arguments and (plain) quotes are also allowed in PassThru insets
953 return !isPassThru();
958 bool InsetText::allowSpellCheck() const
960 return getLayout().spellcheck() && !getLayout().isPassThru();
964 bool InsetText::allowMultiPar() const
966 return getLayout().isMultiPar();
970 bool InsetText::forcePlainLayout(idx_type) const
972 return getLayout().forcePlainLayout();
976 bool InsetText::allowParagraphCustomization(idx_type) const
978 return getLayout().allowParagraphCustomization();
982 bool InsetText::forceLocalFontSwitch() const
984 return getLayout().forceLocalFontSwitch();
988 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
990 ParIterator it2 = it;
992 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
993 if (producesOutput()) {
994 InsetLayout const & il = getLayout();
995 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
996 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
998 // LYXERR0("Entering " << name());
999 cnt.clearLastLayout();
1000 // FIXME cnt.saveLastCounter()?
1002 buffer().updateBuffer(it2, utype, deleted);
1004 // LYXERR0("Exiting " << name());
1005 cnt.restoreLastLayout();
1006 // FIXME cnt.restoreLastCounter()?
1008 // Record if this inset is embedded in a title layout
1009 // This is needed to decide when \maketitle is output.
1010 intitle_context_ = it.paragraph().layout().intitle;
1011 // Also check embedding layouts
1012 size_t const n = it.depth();
1013 for (size_t i = 0; i < n; ++i) {
1014 if (it[i].paragraph().layout().intitle) {
1015 intitle_context_ = true;
1020 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1021 // Note that we do not need to call:
1022 // tclass.counters().clearLastLayout()
1023 // since we are saving and restoring the existing counters, etc.
1024 Counters savecnt = tclass.counters();
1025 tclass.counters().reset();
1026 // we need float information even in note insets (#9760)
1027 tclass.counters().current_float(savecnt.current_float());
1028 tclass.counters().isSubfloat(savecnt.isSubfloat());
1029 buffer().updateBuffer(it2, utype, deleted);
1030 tclass.counters() = move(savecnt);
1035 void InsetText::toString(odocstream & os) const
1037 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1041 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1042 bool const shorten) const
1044 if (!getLayout().isInToc())
1046 text().forOutliner(os, maxlen, shorten);
1050 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1051 UpdateType utype, TocBackend & backend) const
1053 DocIterator dit = cdit;
1054 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1055 iterateForToc(dit, output_active, utype, backend);
1059 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1060 UpdateType utype, TocBackend & backend) const
1062 DocIterator dit = cdit;
1063 // This also ensures that any document has a table of contents
1064 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1066 BufferParams const & bufparams = buffer_->params();
1067 int const min_toclevel = bufparams.documentClass().min_toclevel();
1068 // we really should have done this before we got here, but it
1069 // can't hurt too much to do it again
1070 bool const doing_output = output_active && producesOutput();
1072 // For each paragraph,
1073 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1074 // paragraphs as needed.
1075 // * Traverse its insets and let them add their toc items
1076 // * Compute the main table of contents (this is hardcoded)
1077 // * Add the list of changes
1078 ParagraphList const & pars = paragraphs();
1079 pit_type pend = paragraphs().size();
1080 // Record pairs {start,end} of where a toc item was opened for a paragraph
1081 // and where it must be closed
1082 stack<pair<pit_type, pit_type>> addtotoc_stack;
1084 for (pit_type pit = 0; pit != pend; ++pit) {
1085 Paragraph const & par = pars[pit];
1089 // Custom AddToToc in paragraph layouts (i.e. theorems)
1090 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1092 openAddToTocForParagraph(pit, dit, output_active, backend);
1093 addtotoc_stack.push({pit, end});
1096 // If we find an InsetArgument that is supposed to provide the TOC caption,
1097 // we'll save it for use later.
1098 InsetArgument const * arginset = nullptr;
1099 for (auto const & table : par.insetList()) {
1100 dit.pos() = table.pos;
1101 table.inset->addToToc(dit, doing_output, utype, backend);
1102 if (InsetArgument const * x = table.inset->asInsetArgument())
1103 if (x->isTocCaption())
1107 // End custom AddToToc in paragraph layouts
1108 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1109 // execute the closing function
1110 closeAddToTocForParagraph(addtotoc_stack.top().first,
1111 addtotoc_stack.top().second, backend);
1112 addtotoc_stack.pop();
1115 // now the toc entry for the paragraph in the main table of contents
1116 int const toclevel = text().getTocLevel(pit);
1117 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1118 // insert this into the table of contents
1119 docstring tocstring;
1120 int const length = (doing_output && utype == OutputUpdate) ?
1121 INT_MAX : TOC_ENTRY_LENGTH;
1123 tocstring = par.labelString();
1124 if (!tocstring.empty())
1126 arginset->text().forOutliner(tocstring, length);
1128 par.forOutliner(tocstring, length);
1130 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1131 tocstring, doing_output));
1134 // And now the list of changes.
1135 par.addChangesToToc(dit, buffer(), doing_output, backend);
1140 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1141 DocIterator const & dit,
1143 TocBackend & backend) const
1145 Paragraph const & par = paragraphs()[pit];
1146 TocBuilder & b = backend.builder(par.layout().tocType());
1147 docstring const & label = par.labelString();
1148 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1149 return text().lastInSequence(pit);
1153 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1154 TocBackend & backend) const
1156 Paragraph const & par = paragraphs()[start];
1157 TocBuilder & b = backend.builder(par.layout().tocType());
1158 if (par.layout().isTocCaption()) {
1160 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1161 b.argumentItem(str);
1167 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1169 if (buffer().isClean())
1170 return Inset::notifyCursorLeaves(old, cur);
1172 // find text inset in old cursor
1173 Cursor insetCur = old;
1174 int scriptSlice = insetCur.find(this);
1175 // we can try to continue here. returning true means
1176 // the cursor is "now" invalid. which it was.
1177 LASSERT(scriptSlice != -1, return true);
1178 insetCur.cutOff(scriptSlice);
1179 LASSERT(&insetCur.inset() == this, return true);
1181 // update the old paragraph's words
1182 insetCur.paragraph().updateWords();
1184 return Inset::notifyCursorLeaves(old, cur);
1188 bool InsetText::completionSupported(Cursor const & cur) const
1190 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1191 return text_.completionSupported(cur);
1195 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1197 return completionSupported(cur);
1201 bool InsetText::automaticInlineCompletion() const
1203 return lyxrc.completion_inline_text;
1207 bool InsetText::automaticPopupCompletion() const
1209 return lyxrc.completion_popup_text;
1213 bool InsetText::showCompletionCursor() const
1215 return lyxrc.completion_cursor_text &&
1216 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1220 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1222 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1226 docstring InsetText::completionPrefix(Cursor const & cur) const
1228 if (!completionSupported(cur))
1230 return text_.completionPrefix(cur);
1234 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1237 if (!completionSupported(cur))
1240 return text_.insertCompletion(cur, s, finished);
1244 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1245 Dimension & dim) const
1247 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1248 tm.completionPosAndDim(cur, x, y, dim);
1252 string InsetText::contextMenu(BufferView const &, int, int) const
1254 string context_menu = contextMenuName();
1255 if (context_menu != InsetText::contextMenuName())
1256 context_menu += ";" + InsetText::contextMenuName();
1257 return context_menu;
1261 string InsetText::contextMenuName() const
1263 return "context-edit";
1267 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1269 OutputParams rp(&buffer().params().encoding());
1270 rp.for_tooltip = true;
1271 odocstringstream oss;
1274 ParagraphList::const_iterator beg = paragraphs().begin();
1275 ParagraphList::const_iterator end = paragraphs().end();
1276 ParagraphList::const_iterator it = beg;
1277 bool ref_printed = false;
1279 for (; it != end; ++it) {
1282 if ((*it).isRTL(buffer().params()))
1283 oss << "<div dir=\"rtl\">";
1284 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1285 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1288 docstring str = oss.str();
1290 str += from_ascii("\n\n") + _("[contains tracked changes]");
1291 support::truncateWithEllipsis(str, len);
1296 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1298 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1302 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1304 // Nested cprotect content needs \cprotect
1306 if (producesOutput() && hasCProtectContent(fragile))
1309 // Environments generally need cprotection in fragile context
1310 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1313 if (!getLayout().needsCProtect())
1316 // Environments and "no latex" types (e.g., knitr chunks)
1317 // need cprotection regardless the content
1318 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1321 // If the inset does not produce output (e.g. Note or Branch),
1322 // we can ignore the contained paragraphs
1323 if (!producesOutput())
1326 // Commands need cprotection if they contain specific chars
1327 int const nchars_escape = 9;
1328 static char_type const chars_escape[nchars_escape] = {
1329 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1331 ParagraphList const & pars = paragraphs();
1332 pit_type pend = pit_type(paragraphs().size());
1334 for (pit_type pit = 0; pit != pend; ++pit) {
1335 Paragraph const & par = pars[size_type(pit)];
1336 if (par.needsCProtection(fragile))
1338 docstring const par_str = par.asString();
1339 for (int k = 0; k < nchars_escape; k++) {
1340 if (contains(par_str, chars_escape[k]))