3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetText.h"
15 #include "mathed/MacroTable.h"
17 #include "insets/InsetArgument.h"
18 #include "insets/InsetLayout.h"
19 #include "insets/InsetPreview.h"
21 #include "graphics/PreviewImage.h"
22 #include "graphics/PreviewLoader.h"
24 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "CompletionList.h"
29 #include "CoordCache.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "MetricsInfo.h"
46 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "output_xhtml.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
54 #include "texstream.h"
55 #include "TextClass.h"
57 #include "TextMetrics.h"
58 #include "TocBackend.h"
59 #include "TocBuilder.h"
61 #include "frontends/alert.h"
62 #include "frontends/Painter.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/Changer.h"
70 #include "support/FileName.h"
77 using namespace lyx::support;
82 /////////////////////////////////////////////////////////////////////
84 InsetText::InsetText(Buffer * buf, UsePlain type)
85 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
86 frame_color_(Color_insetframe),
87 text_(this, type == DefaultLayout)
92 InsetText::InsetText(InsetText const & in)
93 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
94 intitle_context_(false), frame_color_(in.frame_color_),
100 void InsetText::setBuffer(Buffer & buf)
102 ParagraphList::iterator end = paragraphs().end();
103 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
104 it->setInsetBuffers(buf);
105 Inset::setBuffer(buf);
109 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
111 text_.setMacrocontextPosition(pos);
113 ParagraphList::const_iterator pit = paragraphs().begin();
114 ParagraphList::const_iterator pend = paragraphs().end();
115 for (; pit != pend; ++pit) {
116 InsetList::const_iterator iit = pit->insetList().begin();
117 InsetList::const_iterator end = pit->insetList().end();
118 for (; iit != end; ++iit) {
119 if (InsetText * txt = iit->inset->asInsetText()) {
120 DocIterator ppos(pos);
121 ppos.push_back(CursorSlice(*txt));
122 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
129 void InsetText::clear()
131 ParagraphList & pars = paragraphs();
132 LBUFERR(!pars.empty());
134 // This is a gross hack...
135 Layout const & old_layout = pars.begin()->layout();
138 pars.push_back(Paragraph());
139 pars.begin()->setInsetOwner(this);
140 pars.begin()->setLayout(old_layout);
144 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
146 TextMetrics const & tm = bv.textMetrics(&text_);
147 Dimension dim = tm.dim();
148 dim.wid += leftOffset(&bv) + rightOffset(&bv);
149 dim.des += bottomOffset(&bv);
150 dim.asc += topOffset(&bv);
155 void InsetText::write(ostream & os) const
162 void InsetText::read(Lexer & lex)
166 // delete the initial paragraph
167 Paragraph oldpar = *paragraphs().begin();
168 paragraphs().clear();
170 lex.setContext("InsetText::read");
171 bool res = text_.read(lex, errorList, this);
174 lex.printError("Missing \\end_inset at this point. ");
177 // ensure we have at least one paragraph.
178 if (paragraphs().empty())
179 paragraphs().push_back(oldpar);
180 // Force default font, if so requested
181 // This avoids paragraphs in buffer language that would have a
182 // foreign language after a document language change, and it ensures
183 // that all new text in ERT and similar gets the "latex" language,
184 // since new text inherits the language from the last position of the
185 // existing text. As a side effect this makes us also robust against
186 // bugs in LyX that might lead to font changes in ERT in .lyx files.
191 void InsetText::setOuterFont(BufferView & bv, FontInfo const & outer) const
193 TextMetrics & tm = bv.textMetrics(&text_);
194 FontInfo tmpfont = getFont();
195 tmpfont.realize(outer);
196 tm.font_.fontInfo() = tmpfont;
200 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
202 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
204 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
206 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
207 mi.base.textwidth -= horiz_offset;
209 // Remember the full outer font
210 setOuterFont(*mi.base.bv, mi.base.font);
211 // and use it in these metrics computation.
212 mi.base.font = tm.font_.fontInfo();
214 // This can happen when a layout has a left and right margin,
215 // and the view is made very narrow. We can't do better than
216 // to draw it partly out of view (bug 5890).
217 if (mi.base.textwidth < 1)
218 mi.base.textwidth = 1;
221 tm.metrics(mi, dim, mi.base.textwidth);
224 mi.base.textwidth += horiz_offset;
225 dim.asc += topOffset(mi.base.bv);
226 dim.des += bottomOffset(mi.base.bv);
227 dim.wid += horiz_offset;
231 void InsetText::draw(PainterInfo & pi, int x, int y) const
233 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
235 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
236 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
237 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
238 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
239 int const xframe = x + leftOffset(pi.base.bv) / 2;
240 bool change_drawn = false;
242 pi.pain.fillRectangle(xframe, yframe, w, h,
243 pi.backgroundColor(this));
246 Changer dummy = changeVar(pi.background_color,
247 pi.backgroundColor(this, false));
248 // The change tracking cue must not be inherited
249 Changer dummy2 = changeVar(pi.change, Change());
250 tm.draw(pi, x + leftOffset(pi.base.bv), y);
254 // Change color of the frame in tracked changes, like for tabulars.
255 // Only do so if the color is not custom. But do so even if RowPainter
256 // handles the strike-through already.
258 if (pi.change.changed()
259 // Originally, these are the colors with role Text, from role() in
260 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
261 // types, and also maybe it need not match in the future.
262 && (frameColor() == Color_foreground
263 || frameColor() == Color_cursor
264 || frameColor() == Color_preview
265 || frameColor() == Color_tabularline
266 || frameColor() == Color_previewframe)) {
267 c = pi.change.color();
271 pi.pain.rectangle(xframe, yframe, w, h, c);
274 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
275 // Do not draw the change tracking cue if already done by RowPainter and
276 // do not draw the cue for INSERTED if the information is already in the
277 // color of the frame
278 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
282 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
284 pit_type const pit = front ? 0 : paragraphs().size() - 1;
285 pos_type pos = front ? 0 : paragraphs().back().size();
287 // if visual information is not to be ignored, move to extreme right/left
288 if (entry_from != ENTRY_DIRECTION_IGNORE) {
289 Cursor temp_cur = cur;
290 temp_cur.pit() = pit;
291 temp_cur.pos() = pos;
292 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
293 pos = temp_cur.pos();
296 cur.top().setPitPos(pit, pos);
297 cur.setCurrentFont();
302 Inset * InsetText::editXY(Cursor & cur, int x, int y)
304 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
308 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
310 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
313 // See bug #9042, for instance.
315 // Force any new text to latex_language FIXME: This
316 // should only be necessary in constructor, but new
317 // paragraphs that are created by pressing enter at
318 // the start of an existing paragraph get the buffer
319 // language and not latex_language, so we take this
320 // brute force approach.
321 cur.current_font.setLanguage(latex_language);
322 cur.real_current_font.setLanguage(latex_language);
326 switch (cmd.action()) {
328 case LFUN_CLIPBOARD_PASTE:
329 case LFUN_SELECTION_PASTE:
330 case LFUN_PRIMARY_SELECTION_PASTE:
331 text_.dispatch(cur, cmd);
332 // If we we can only store plain text, we must reset all
334 // FIXME: Change only the pasted paragraphs
338 case LFUN_INSET_SPLIT:
339 case LFUN_INSET_DISSOLVE: {
340 bool const main_inset = text_.isMainText();
341 bool const target_inset = cmd.argument().empty()
342 || cmd.getArg(0) == insetName(lyxCode());
344 if (!main_inset && target_inset) {
345 UndoGroupHelper ugh(&buffer());
346 // Text::dissolveInset assumes that the cursor
347 // is inside the Inset.
348 if (&cur.inset() != this) {
350 cur.pushBackward(*this);
352 text_.dispatch(cur, cmd);
359 text_.dispatch(cur, cmd);
362 if (!cur.result().dispatched())
363 Inset::doDispatch(cur, cmd);
367 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
368 FuncStatus & status) const
370 switch (cmd.action()) {
371 case LFUN_INSET_SPLIT:
372 case LFUN_INSET_DISSOLVE: {
373 bool const main_inset = text_.isMainText();
374 bool const target_inset = cmd.argument().empty()
375 || cmd.getArg(0) == insetName(lyxCode());
378 status.setEnabled(!main_inset);
382 case LFUN_ARGUMENT_INSERT: {
383 string const arg = cmd.getArg(0);
385 status.setEnabled(false);
388 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
389 return text_.getStatus(cur, cmd, status);
391 Layout::LaTeXArgMap args = getLayout().args();
392 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
393 if (lait != args.end()) {
394 status.setEnabled(true);
395 for (Paragraph const & par : paragraphs())
396 for (auto const & table : par.insetList())
397 if (InsetArgument const * ins = table.inset->asInsetArgument())
398 if (ins->name() == arg) {
399 // we have this already
400 status.setEnabled(false);
404 status.setEnabled(false);
409 // Dispatch only to text_ if the cursor is inside
410 // the text_. It is not for context menus (bug 5797).
412 if (cur.text() == &text_)
413 ret = text_.getStatus(cur, cmd, status);
416 ret = Inset::getStatus(cur, cmd, status);
422 void InsetText::fixParagraphsFont()
424 Font font(inherit_font, buffer().params().language);
425 font.setLanguage(latex_language);
426 ParagraphList::iterator par = paragraphs().begin();
427 ParagraphList::iterator const end = paragraphs().end();
429 if (par->isPassThru())
430 par->resetFonts(font);
431 if (!par->allowParagraphCustomization())
432 par->params().clear();
438 // bool InsetText::isChanged() const
440 // ParagraphList::const_iterator pit = paragraphs().begin();
441 // ParagraphList::const_iterator end = paragraphs().end();
442 // for (; pit != end; ++pit) {
443 // if (pit->isChanged())
450 void InsetText::setChange(Change const & change)
452 ParagraphList::iterator pit = paragraphs().begin();
453 ParagraphList::iterator end = paragraphs().end();
454 for (; pit != end; ++pit) {
455 pit->setChange(change);
460 void InsetText::acceptChanges()
462 text_.acceptChanges();
466 void InsetText::rejectChanges()
468 text_.rejectChanges();
472 void InsetText::validate(LaTeXFeatures & features) const
474 features.useInsetLayout(getLayout());
475 for (Paragraph const & p : paragraphs())
476 p.validate(features);
480 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
482 // This implements the standard way of handling the LaTeX
483 // output of a text inset, either a command or an
484 // environment. Standard collapsible insets should not
485 // redefine this, non-standard ones may call this.
486 InsetLayout const & il = getLayout();
487 if (il.forceOwnlines())
489 bool needendgroup = false;
490 if (!il.latexname().empty()) {
491 if (il.latextype() == InsetLaTeXType::COMMAND) {
493 // FIXME \protect should only be used for fragile
494 // commands, but we do not provide this information yet.
495 if (hasCProtectContent(runparams.moving_arg)) {
496 if (contains(runparams.active_chars, '^')) {
497 // cprotect relies on ^ being on catcode 7
498 os << "\\begingroup\\catcode`\\^=7";
502 } else if (runparams.moving_arg)
504 os << '\\' << from_utf8(il.latexname());
505 if (!il.latexargs().empty())
506 getArgs(os, runparams);
507 if (!il.latexparam().empty())
508 os << from_utf8(il.latexparam());
510 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
515 if (runparams.lastid != -1)
516 os.texrow().start(runparams.lastid,
518 os << "\\begin{" << from_utf8(il.latexname()) << "}";
519 if (!il.latexargs().empty())
520 getArgs(os, runparams);
521 if (!il.latexparam().empty())
522 os << from_utf8(il.latexparam());
526 if (!il.latexargs().empty())
527 getArgs(os, runparams);
528 if (!il.latexparam().empty())
529 os << from_utf8(il.latexparam());
532 if (!il.leftdelim().empty())
533 os << il.leftdelim();
535 OutputParams rp = runparams;
538 if (il.isNeedProtect())
539 rp.moving_arg = true;
540 if (il.isNeedMBoxProtect())
542 if (!il.passThruChars().empty())
543 rp.pass_thru_chars += il.passThruChars();
544 if (!il.newlineCmd().empty())
545 rp.newlinecmd = il.newlineCmd();
547 rp.par_end = paragraphs().size();
549 // Output the contents of the inset
550 latexParagraphs(buffer(), text_, os, rp);
551 runparams.encoding = rp.encoding;
552 // Pass the post_macros upstream
553 runparams.post_macro = rp.post_macro;
554 // These need to be passed upstream as well
555 runparams.need_maketitle = rp.need_maketitle;
556 runparams.have_maketitle = rp.have_maketitle;
558 if (!il.rightdelim().empty())
559 os << il.rightdelim();
561 if (!il.latexname().empty()) {
562 if (il.latextype() == InsetLaTeXType::COMMAND) {
564 if (!il.postcommandargs().empty())
565 getArgs(os, runparams, true);
568 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
569 // A comment environment doesn't need a % before \n\end
570 if (il.isDisplay() || runparams.inComment)
574 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
576 os.protectSpace(true);
579 if (il.forceOwnlines())
584 int InsetText::plaintext(odocstringstream & os,
585 OutputParams const & runparams, size_t max_length) const
587 ParagraphList::const_iterator beg = paragraphs().begin();
588 ParagraphList::const_iterator end = paragraphs().end();
589 ParagraphList::const_iterator it = beg;
590 bool ref_printed = false;
592 for (; it != end; ++it) {
595 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
598 odocstringstream oss;
599 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
600 docstring const str = oss.str();
602 // FIXME: len is not computed fully correctly; in principle,
603 // we have to count the characters after the last '\n'
605 if (os.str().size() >= max_length)
613 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
615 docbook(xs, rp, WriteEverything);
619 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
621 // Always output all the paragraphs.
622 OutputParams runparams = rp;
623 runparams.par_begin = 0;
624 runparams.par_end = text().paragraphs().size();
627 xs.startDivision(false);
628 docbookParagraphs(text_, buffer(), xs, runparams);
633 InsetLayout const &il = getLayout();
635 // Maybe this is an <info> paragraph that should not be generated
636 // at all (i.e. right now, its place is somewhere else, typically outside
637 // the current paragraph).
638 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
641 // Maybe this inset must be rendered before being output.
642 if (il.docbookrenderasimage()) {
643 docbookRenderAsImage(xs, runparams, opts);
647 // If none of the special cases before apply, output the inset.
648 docbookText(xs, runparams, opts);
652 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
654 LASSERT(getLayout().docbookrenderasimage(), return);
656 // Generate the LaTeX code to compile in order to get the image.
657 // This code actually does the same as an InsetPreview, but without
659 // Also, the image must be generated before the DocBook output is finished,
660 // unlike a preview that is not immediately required for display.
661 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
662 std::string const snippet = support::trim(to_utf8(latex_snippet));
663 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
665 graphics::PreviewLoader* loader = buffer().loader();
666 loader->add(snippet);
667 loader->startLoading(true); // Generate the image and wait until done.
668 graphics::PreviewImage const * img = loader->preview(snippet);
669 LASSERT(img != nullptr, return);
670 support::FileName const & filename = img->filename();
672 // Copy the image into the right folder.
673 rp.exportdata->addExternalFile("docbook5", filename, filename.onlyFileName());
675 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
676 // Start writing the DocBook code for the image.
677 xs << xml::StartTag("mediaobject")
680 // Output the rendered inset.
681 xs << xml::StartTag("imageobject")
683 << xml::CompTag("imagedata", std::string("fileref='") + filename.onlyFileName() + "'")
685 << xml::EndTag("imageobject")
688 // Output the raw content.
689 xs << xml::StartTag("textobject")
691 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
692 docbookText(xs, rp, opts);
693 xs << xml::EndTag("programlisting")
695 << xml::EndTag("textobject")
698 xs << xml::EndTag("mediaobject");
702 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
704 InsetLayout const &il = getLayout();
705 OutputParams runparams = rp;
707 // In some cases, the input parameters must be overridden for outer tags.
708 bool writeOuterTag = opts & WriteOuterTag;
710 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
711 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
712 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
713 auto parSize = (size_t) par.size();
714 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
716 writeOuterTag = !allBibitems;
719 // Detect arguments that should be output before/after the paragraph.
720 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
721 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
722 std::set<InsetArgument const *> prependedArguments;
723 for (auto const & par : paragraphs()) {
724 for (pos_type i = 0; i < par.size(); ++i) {
725 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
726 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
727 if (arg->docbookargumentbeforemaintag())
728 prependedArguments.insert(par.getInset(i)->asInsetArgument());
733 std::set<InsetArgument const *> appendedArguments;
734 for (auto const & par : paragraphs()) {
735 for (pos_type i = 0; i < par.size(); ++i) {
736 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
737 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
738 if (arg->docbookargumentaftermaintag())
739 appendedArguments.insert(par.getInset(i)->asInsetArgument());
744 // Start outputting this inset.
745 // - First, wrapper around the inset and its main tag.
747 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
748 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
750 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
751 docstring attrs = docstring();
752 if (!il.docbookattr().empty())
753 attrs += from_ascii(il.docbookattr());
754 if (il.docbooktag() == "link")
755 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
756 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
759 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
760 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
763 // - Think about the arguments before the paragraph.
764 OutputParams np = runparams;
765 np.docbook_in_par = true;
766 for (auto const & arg : prependedArguments)
767 arg->docbook(xs, np);
769 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
770 runparams.docbook_prepended_arguments = std::move(prependedArguments);
771 runparams.docbook_appended_arguments = appendedArguments;
773 // - Deal with the first item.
774 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
776 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
777 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
779 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
780 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
783 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
785 // With respect to XHTML, paragraphs are still allowed here.
786 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
787 runparams.docbook_make_pars = false;
789 runparams.pass_thru = true;
791 // - Write the main content of the inset.
792 xs.startDivision(false);
793 docbookParagraphs(text_, buffer(), xs, runparams);
796 // - Think about the arguments after the paragraph.
797 for (auto const & arg : appendedArguments)
798 arg->docbook(xs, np);
800 // - Close the required tags.
802 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
803 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
805 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
806 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
808 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
809 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
811 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
812 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
814 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
815 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
820 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
822 return insetAsXHTML(xs, runparams, WriteEverything);
827 // There are cases where we may need to close open fonts and such
828 // and then re-open them when we are done. This would be the case, e.g.,
829 // if we were otherwise about to write:
830 // <em>word <div class='foot'>footnote text.</div> emph</em>
831 // The problem isn't so much that the footnote text will get emphasized:
832 // we can handle that with CSS. The problem is that this is invalid XHTML.
833 // One solution would be to make the footnote <span>, but the problem is
834 // completely general, and so we'd have to make absolutely everything into
835 // span. What I think will work is to check if we're about to write "div" and,
836 // if so, try to close fonts, etc.
837 // There are probably limits to how well we can do here, though, and we will
838 // have to rely upon users not putting footnotes inside noun-type insets.
839 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
840 XHTMLOptions opts) const
842 // we will always want to output all our paragraphs when we are
844 OutputParams runparams = rp;
845 runparams.par_begin = 0;
846 runparams.par_end = text().paragraphs().size();
849 xs.startDivision(false);
850 xhtmlParagraphs(text_, buffer(), xs, runparams);
855 InsetLayout const & il = getLayout();
856 if (opts & WriteOuterTag)
857 xs << xml::StartTag(il.htmltag(), il.htmlattr());
859 if ((opts & WriteLabel) && !il.counter().empty()) {
860 BufferParams const & bp = buffer().masterBuffer()->params();
861 Counters & cntrs = bp.documentClass().counters();
862 cntrs.step(il.counter(), OutputUpdate);
863 // FIXME: translate to paragraph language
864 if (!il.htmllabel().empty()) {
865 docstring const lbl =
866 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
867 // FIXME is this check necessary?
869 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
871 xs << xml::EndTag(il.htmllabeltag());
876 if (opts & WriteInnerTag)
877 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
879 // we will eventually lose information about the containing inset
880 if (!allowMultiPar() || opts == JustText)
881 runparams.html_make_pars = false;
883 runparams.pass_thru = true;
885 xs.startDivision(false);
886 xhtmlParagraphs(text_, buffer(), xs, runparams);
889 if (opts & WriteInnerTag)
890 xs << xml::EndTag(il.htmlinnertag());
892 if (opts & WriteOuterTag)
893 xs << xml::EndTag(il.htmltag());
899 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
900 bool const post) const
902 OutputParams runparams = runparams_in;
903 runparams.local_font =
904 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
906 runparams.pass_thru = true;
908 latexArgInsetsForParent(paragraphs(), os, runparams,
909 getLayout().postcommandargs(), "post:");
911 latexArgInsetsForParent(paragraphs(), os, runparams,
912 getLayout().latexargs());
916 void InsetText::cursorPos(BufferView const & bv,
917 CursorSlice const & sl, bool boundary, int & x, int & y) const
919 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
920 y = bv.textMetrics(&text_).cursorY(sl, boundary);
924 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
927 Paragraph & first = paragraphs().front();
928 for (unsigned int i = 0; i < data.length(); ++i)
929 first.insertChar(i, data[i], font, trackChanges);
933 void InsetText::setDrawFrame(bool flag)
939 ColorCode InsetText::frameColor() const
945 void InsetText::setFrameColor(ColorCode col)
951 void InsetText::appendParagraphs(ParagraphList & plist)
953 // There is little we can do here to keep track of changes.
954 // As of 2006/10/20, appendParagraphs is used exclusively by
955 // LyXTabular::setMultiColumn. In this context, the paragraph break
956 // is lost irreversibly and the appended text doesn't really change
958 ParagraphList & pl = paragraphs();
960 ParagraphList::iterator pit = plist.begin();
961 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
963 mergeParagraph(buffer().params(), pl,
964 distance(pl.begin(), ins) - 1);
966 ParagraphList::iterator const pend = plist.end();
967 for (; pit != pend; ++pit)
972 void InsetText::addPreview(DocIterator const & text_inset_pos,
973 graphics::PreviewLoader & loader) const
975 ParagraphList::const_iterator pit = paragraphs().begin();
976 ParagraphList::const_iterator pend = paragraphs().end();
979 DocIterator inset_pos = text_inset_pos;
980 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
982 for (; pit != pend; ++pit, ++pidx) {
983 InsetList::const_iterator it = pit->insetList().begin();
984 InsetList::const_iterator end = pit->insetList().end();
985 inset_pos.pit() = pidx;
986 for (; it != end; ++it) {
987 inset_pos.pos() = it->pos;
988 it->inset->addPreview(inset_pos, loader);
994 ParagraphList const & InsetText::paragraphs() const
996 return text_.paragraphs();
1000 ParagraphList & InsetText::paragraphs()
1002 return text_.paragraphs();
1006 bool InsetText::hasCProtectContent(bool fragile) const
1008 fragile |= getLayout().isNeedProtect();
1009 ParagraphList const & pars = paragraphs();
1010 pit_type pend = pit_type(paragraphs().size());
1011 for (pit_type pit = 0; pit != pend; ++pit) {
1012 Paragraph const & par = pars[size_type(pit)];
1013 if (par.needsCProtection(fragile))
1020 bool InsetText::insetAllowed(InsetCode code) const
1023 // Arguments, (plain) quotes and counter insets
1024 // are also allowed in PassThru insets
1030 return !isPassThru();
1035 bool InsetText::allowSpellCheck() const
1037 return getLayout().spellcheck() && !getLayout().isPassThru();
1041 bool InsetText::allowMultiPar() const
1043 return getLayout().isMultiPar();
1047 bool InsetText::forcePlainLayout(idx_type) const
1049 return getLayout().forcePlainLayout();
1053 bool InsetText::allowParagraphCustomization(idx_type) const
1055 return getLayout().allowParagraphCustomization();
1059 bool InsetText::forceLocalFontSwitch() const
1061 return getLayout().forceLocalFontSwitch();
1065 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1067 ParIterator it2 = it;
1069 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1070 if (producesOutput()) {
1071 InsetLayout const & il = getLayout();
1072 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1073 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1075 // LYXERR0("Entering " << name());
1076 cnt.clearLastLayout();
1077 // FIXME cnt.saveLastCounter()?
1079 buffer().updateBuffer(it2, utype, deleted);
1081 // LYXERR0("Exiting " << name());
1082 cnt.restoreLastLayout();
1083 // FIXME cnt.restoreLastCounter()?
1085 // Record if this inset is embedded in a title layout
1086 // This is needed to decide when \maketitle is output.
1087 intitle_context_ = it.paragraph().layout().intitle;
1088 // Also check embedding layouts
1089 size_t const n = it.depth();
1090 for (size_t i = 0; i < n; ++i) {
1091 if (it[i].paragraph().layout().intitle) {
1092 intitle_context_ = true;
1097 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1098 // Note that we do not need to call:
1099 // tclass.counters().clearLastLayout()
1100 // since we are saving and restoring the existing counters, etc.
1101 Counters savecnt = tclass.counters();
1102 tclass.counters().reset();
1103 // we need float information even in note insets (#9760)
1104 tclass.counters().current_float(savecnt.current_float());
1105 tclass.counters().isSubfloat(savecnt.isSubfloat());
1106 buffer().updateBuffer(it2, utype, deleted);
1107 tclass.counters() = move(savecnt);
1112 void InsetText::toString(odocstream & os) const
1114 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1118 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1119 bool const shorten) const
1121 if (!getLayout().isInToc())
1123 text().forOutliner(os, maxlen, shorten);
1127 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1128 UpdateType utype, TocBackend & backend) const
1130 DocIterator dit = cdit;
1131 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1132 iterateForToc(dit, output_active, utype, backend);
1136 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1137 UpdateType utype, TocBackend & backend) const
1139 DocIterator dit = cdit;
1140 // This also ensures that any document has a table of contents
1141 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1143 BufferParams const & bufparams = buffer_->params();
1144 int const min_toclevel = bufparams.documentClass().min_toclevel();
1145 // we really should have done this before we got here, but it
1146 // can't hurt too much to do it again
1147 bool const doing_output = output_active && producesOutput();
1149 // For each paragraph,
1150 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1151 // paragraphs as needed.
1152 // * Traverse its insets and let them add their toc items
1153 // * Compute the main table of contents (this is hardcoded)
1154 // * Add the list of changes
1155 ParagraphList const & pars = paragraphs();
1156 pit_type pend = paragraphs().size();
1157 // Record pairs {start,end} of where a toc item was opened for a paragraph
1158 // and where it must be closed
1159 stack<pair<pit_type, pit_type>> addtotoc_stack;
1161 for (pit_type pit = 0; pit != pend; ++pit) {
1162 Paragraph const & par = pars[pit];
1166 // Custom AddToToc in paragraph layouts (i.e. theorems)
1167 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1169 openAddToTocForParagraph(pit, dit, output_active, backend);
1170 addtotoc_stack.push({pit, end});
1173 // If we find an InsetArgument that is supposed to provide the TOC caption,
1174 // we'll save it for use later.
1175 InsetArgument const * arginset = nullptr;
1176 for (auto const & table : par.insetList()) {
1177 dit.pos() = table.pos;
1178 table.inset->addToToc(dit, doing_output, utype, backend);
1179 if (InsetArgument const * x = table.inset->asInsetArgument())
1180 if (x->isTocCaption())
1184 // End custom AddToToc in paragraph layouts
1185 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1186 // execute the closing function
1187 closeAddToTocForParagraph(addtotoc_stack.top().first,
1188 addtotoc_stack.top().second, backend);
1189 addtotoc_stack.pop();
1192 // now the toc entry for the paragraph in the main table of contents
1193 int const toclevel = text().getTocLevel(pit);
1194 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1195 // insert this into the table of contents
1196 docstring tocstring;
1197 int const length = (doing_output && utype == OutputUpdate) ?
1198 INT_MAX : TOC_ENTRY_LENGTH;
1200 tocstring = par.labelString();
1201 if (!tocstring.empty())
1203 arginset->text().forOutliner(tocstring, length);
1205 par.forOutliner(tocstring, length);
1207 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1208 tocstring, doing_output));
1211 // And now the list of changes.
1212 par.addChangesToToc(dit, buffer(), doing_output, backend);
1217 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1218 DocIterator const & dit,
1220 TocBackend & backend) const
1222 Paragraph const & par = paragraphs()[pit];
1223 TocBuilder & b = backend.builder(par.layout().tocType());
1224 docstring const & label = par.labelString();
1225 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1226 return text().lastInSequence(pit);
1230 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1231 TocBackend & backend) const
1233 Paragraph const & par = paragraphs()[start];
1234 TocBuilder & b = backend.builder(par.layout().tocType());
1235 if (par.layout().isTocCaption()) {
1237 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1238 b.argumentItem(str);
1244 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1246 if (buffer().isClean())
1247 return Inset::notifyCursorLeaves(old, cur);
1249 // find text inset in old cursor
1250 Cursor insetCur = old;
1251 int scriptSlice = insetCur.find(this);
1252 // we can try to continue here. returning true means
1253 // the cursor is "now" invalid. which it was.
1254 LASSERT(scriptSlice != -1, return true);
1255 insetCur.cutOff(scriptSlice);
1256 LASSERT(&insetCur.inset() == this, return true);
1258 // update the old paragraph's words
1259 insetCur.paragraph().updateWords();
1261 return Inset::notifyCursorLeaves(old, cur);
1265 bool InsetText::completionSupported(Cursor const & cur) const
1267 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1268 return text_.completionSupported(cur);
1272 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1274 return completionSupported(cur);
1278 bool InsetText::automaticInlineCompletion() const
1280 return lyxrc.completion_inline_text;
1284 bool InsetText::automaticPopupCompletion() const
1286 return lyxrc.completion_popup_text;
1290 bool InsetText::showCompletionCursor() const
1292 return lyxrc.completion_cursor_text &&
1293 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1297 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1299 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1303 docstring InsetText::completionPrefix(Cursor const & cur) const
1305 if (!completionSupported(cur))
1307 return text_.completionPrefix(cur);
1311 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1314 if (!completionSupported(cur))
1317 return text_.insertCompletion(cur, s, finished);
1321 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1322 Dimension & dim) const
1324 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1325 tm.completionPosAndDim(cur, x, y, dim);
1329 string InsetText::contextMenu(BufferView const &, int, int) const
1331 string context_menu = contextMenuName();
1332 if (context_menu != InsetText::contextMenuName())
1333 context_menu += ";" + InsetText::contextMenuName();
1334 return context_menu;
1338 string InsetText::contextMenuName() const
1340 return "context-edit";
1344 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1346 OutputParams rp(&buffer().params().encoding());
1347 rp.for_tooltip = true;
1348 odocstringstream oss;
1351 ParagraphList::const_iterator beg = paragraphs().begin();
1352 ParagraphList::const_iterator end = paragraphs().end();
1353 ParagraphList::const_iterator it = beg;
1354 bool ref_printed = false;
1356 for (; it != end; ++it) {
1359 if ((*it).isRTL(buffer().params()))
1360 oss << "<div dir=\"rtl\">";
1361 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1362 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1365 docstring str = oss.str();
1367 str += from_ascii("\n\n") + _("[contains tracked changes]");
1368 support::truncateWithEllipsis(str, len);
1373 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1375 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1379 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1381 // Nested cprotect content needs \cprotect
1383 if (producesOutput() && hasCProtectContent(fragile))
1386 // Environments generally need cprotection in fragile context
1387 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1390 if (!getLayout().needsCProtect())
1393 // Environments and "no latex" types (e.g., knitr chunks)
1394 // need cprotection regardless the content
1395 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1398 // If the inset does not produce output (e.g. Note or Branch),
1399 // we can ignore the contained paragraphs
1400 if (!producesOutput())
1403 // Commands need cprotection if they contain specific chars
1404 int const nchars_escape = 9;
1405 static char_type const chars_escape[nchars_escape] = {
1406 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1408 ParagraphList const & pars = paragraphs();
1409 pit_type pend = pit_type(paragraphs().size());
1411 for (pit_type pit = 0; pit != pend; ++pit) {
1412 Paragraph const & par = pars[size_type(pit)];
1413 if (par.needsCProtection(fragile))
1415 docstring const par_str = par.asString();
1416 for (int k = 0; k < nchars_escape; k++) {
1417 if (contains(par_str, chars_escape[k]))