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/filetools.h"
67 #include "support/gettext.h"
68 #include "support/lassert.h"
69 #include "support/lstrings.h"
70 #include "support/Changer.h"
71 #include "support/FileName.h"
78 using namespace lyx::support;
83 /////////////////////////////////////////////////////////////////////
85 InsetText::InsetText(Buffer * buf, UsePlain type)
86 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
87 frame_color_(Color_insetframe),
88 text_(this, type == DefaultLayout)
93 InsetText::InsetText(InsetText const & in)
94 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
95 intitle_context_(false), frame_color_(in.frame_color_),
101 void InsetText::setBuffer(Buffer & buf)
103 ParagraphList::iterator end = paragraphs().end();
104 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
105 it->setInsetBuffers(buf);
106 Inset::setBuffer(buf);
110 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
112 text_.setMacrocontextPosition(pos);
114 ParagraphList::const_iterator pit = paragraphs().begin();
115 ParagraphList::const_iterator pend = paragraphs().end();
116 for (; pit != pend; ++pit) {
117 InsetList::const_iterator iit = pit->insetList().begin();
118 InsetList::const_iterator end = pit->insetList().end();
119 for (; iit != end; ++iit) {
120 if (InsetText * txt = iit->inset->asInsetText()) {
121 DocIterator ppos(pos);
122 ppos.push_back(CursorSlice(*txt));
123 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
130 void InsetText::clear()
132 ParagraphList & pars = paragraphs();
133 LBUFERR(!pars.empty());
135 // This is a gross hack...
136 Layout const & old_layout = pars.begin()->layout();
139 pars.push_back(Paragraph());
140 pars.begin()->setInsetOwner(this);
141 pars.begin()->setLayout(old_layout);
145 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
147 TextMetrics const & tm = bv.textMetrics(&text_);
148 Dimension dim = tm.dim();
149 dim.wid += leftOffset(&bv) + rightOffset(&bv);
150 dim.des += bottomOffset(&bv);
151 dim.asc += topOffset(&bv);
156 void InsetText::write(ostream & os) const
163 void InsetText::read(Lexer & lex)
167 // delete the initial paragraph
168 Paragraph oldpar = *paragraphs().begin();
169 paragraphs().clear();
171 lex.setContext("InsetText::read");
172 bool res = text_.read(lex, errorList, this);
175 lex.printError("Missing \\end_inset at this point. ");
178 // ensure we have at least one paragraph.
179 if (paragraphs().empty())
180 paragraphs().push_back(oldpar);
181 // Force default font, if so requested
182 // This avoids paragraphs in buffer language that would have a
183 // foreign language after a document language change, and it ensures
184 // that all new text in ERT and similar gets the "latex" language,
185 // since new text inherits the language from the last position of the
186 // existing text. As a side effect this makes us also robust against
187 // bugs in LyX that might lead to font changes in ERT in .lyx files.
192 void InsetText::setOuterFont(BufferView & bv, FontInfo const & outer) const
194 TextMetrics & tm = bv.textMetrics(&text_);
195 FontInfo tmpfont = getFont();
196 tmpfont.realize(outer);
197 tm.font_.fontInfo() = tmpfont;
201 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
203 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
205 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
207 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
208 mi.base.textwidth -= horiz_offset;
210 // Remember the full outer font
211 setOuterFont(*mi.base.bv, mi.base.font);
212 // and use it in these metrics computation.
213 mi.base.font = tm.font_.fontInfo();
215 // This can happen when a layout has a left and right margin,
216 // and the view is made very narrow. We can't do better than
217 // to draw it partly out of view (bug 5890).
218 if (mi.base.textwidth < 1)
219 mi.base.textwidth = 1;
222 tm.metrics(mi, dim, mi.base.textwidth);
225 mi.base.textwidth += horiz_offset;
226 dim.asc += topOffset(mi.base.bv);
227 dim.des += bottomOffset(mi.base.bv);
228 dim.wid += horiz_offset;
232 void InsetText::draw(PainterInfo & pi, int x, int y) const
234 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
236 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
237 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
238 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
239 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
240 int const xframe = x + leftOffset(pi.base.bv) / 2;
241 bool change_drawn = false;
243 pi.pain.fillRectangle(xframe, yframe, w, h,
244 pi.backgroundColor(this));
247 Changer dummy = changeVar(pi.background_color,
248 pi.backgroundColor(this, false));
249 // The change tracking cue must not be inherited
250 Changer dummy2 = changeVar(pi.change, Change());
251 tm.draw(pi, x + leftOffset(pi.base.bv), y);
255 // Change color of the frame in tracked changes, like for tabulars.
256 // Only do so if the color is not custom. But do so even if RowPainter
257 // handles the strike-through already.
259 if (pi.change.changed()
260 // Originally, these are the colors with role Text, from role() in
261 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
262 // types, and also maybe it need not match in the future.
263 && (frameColor() == Color_foreground
264 || frameColor() == Color_cursor
265 || frameColor() == Color_preview
266 || frameColor() == Color_tabularline
267 || frameColor() == Color_previewframe)) {
268 c = pi.change.color();
272 pi.pain.rectangle(xframe, yframe, w, h, c);
275 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
276 // Do not draw the change tracking cue if already done by RowPainter and
277 // do not draw the cue for INSERTED if the information is already in the
278 // color of the frame
279 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
283 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
285 pit_type const pit = front ? 0 : paragraphs().size() - 1;
286 pos_type pos = front ? 0 : paragraphs().back().size();
288 // if visual information is not to be ignored, move to extreme right/left
289 if (entry_from != ENTRY_DIRECTION_IGNORE) {
290 Cursor temp_cur = cur;
291 temp_cur.pit() = pit;
292 temp_cur.pos() = pos;
293 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
294 pos = temp_cur.pos();
297 cur.top().setPitPos(pit, pos);
298 cur.setCurrentFont();
303 Inset * InsetText::editXY(Cursor & cur, int x, int y)
305 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
309 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
311 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
314 // See bug #9042, for instance.
316 // Force any new text to latex_language FIXME: This
317 // should only be necessary in constructor, but new
318 // paragraphs that are created by pressing enter at
319 // the start of an existing paragraph get the buffer
320 // language and not latex_language, so we take this
321 // brute force approach.
322 cur.current_font.setLanguage(latex_language);
323 cur.real_current_font.setLanguage(latex_language);
327 switch (cmd.action()) {
329 case LFUN_CLIPBOARD_PASTE:
330 case LFUN_SELECTION_PASTE:
331 case LFUN_PRIMARY_SELECTION_PASTE:
332 text_.dispatch(cur, cmd);
333 // If we we can only store plain text, we must reset all
335 // FIXME: Change only the pasted paragraphs
339 case LFUN_INSET_SPLIT:
340 case LFUN_INSET_DISSOLVE: {
341 bool const main_inset = text_.isMainText();
342 bool const target_inset = cmd.argument().empty()
343 || cmd.getArg(0) == insetName(lyxCode());
345 if (!main_inset && target_inset) {
346 UndoGroupHelper ugh(&buffer());
347 // Text::dissolveInset assumes that the cursor
348 // is inside the Inset.
349 if (&cur.inset() != this) {
351 cur.pushBackward(*this);
353 text_.dispatch(cur, cmd);
360 text_.dispatch(cur, cmd);
363 if (!cur.result().dispatched())
364 Inset::doDispatch(cur, cmd);
368 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
369 FuncStatus & status) const
371 switch (cmd.action()) {
372 case LFUN_INSET_SPLIT:
373 case LFUN_INSET_DISSOLVE: {
374 bool const main_inset = text_.isMainText();
375 bool const target_inset = cmd.argument().empty()
376 || cmd.getArg(0) == insetName(lyxCode());
379 status.setEnabled(!main_inset);
383 case LFUN_ARGUMENT_INSERT: {
384 string const arg = cmd.getArg(0);
386 status.setEnabled(false);
389 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
390 return text_.getStatus(cur, cmd, status);
392 Layout::LaTeXArgMap args = getLayout().args();
393 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
394 if (lait != args.end()) {
395 status.setEnabled(true);
396 for (Paragraph const & par : paragraphs())
397 for (auto const & table : par.insetList())
398 if (InsetArgument const * ins = table.inset->asInsetArgument())
399 if (ins->name() == arg) {
400 // we have this already
401 status.setEnabled(false);
405 status.setEnabled(false);
410 // Dispatch only to text_ if the cursor is inside
411 // the text_. It is not for context menus (bug 5797).
413 if (cur.text() == &text_)
414 ret = text_.getStatus(cur, cmd, status);
417 ret = Inset::getStatus(cur, cmd, status);
423 void InsetText::fixParagraphsFont()
425 Font font(inherit_font, buffer().params().language);
426 font.setLanguage(latex_language);
427 ParagraphList::iterator par = paragraphs().begin();
428 ParagraphList::iterator const end = paragraphs().end();
430 if (par->isPassThru())
431 par->resetFonts(font);
432 if (!par->allowParagraphCustomization())
433 par->params().clear();
439 // bool InsetText::isChanged() const
441 // ParagraphList::const_iterator pit = paragraphs().begin();
442 // ParagraphList::const_iterator end = paragraphs().end();
443 // for (; pit != end; ++pit) {
444 // if (pit->isChanged())
451 void InsetText::setChange(Change const & change)
453 ParagraphList::iterator pit = paragraphs().begin();
454 ParagraphList::iterator end = paragraphs().end();
455 for (; pit != end; ++pit) {
456 pit->setChange(change);
461 void InsetText::acceptChanges()
463 text_.acceptChanges();
467 void InsetText::rejectChanges()
469 text_.rejectChanges();
473 void InsetText::validate(LaTeXFeatures & features) const
475 features.useInsetLayout(getLayout());
476 for (Paragraph const & p : paragraphs())
477 p.validate(features);
481 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
483 // This implements the standard way of handling the LaTeX
484 // output of a text inset, either a command or an
485 // environment. Standard collapsible insets should not
486 // redefine this, non-standard ones may call this.
487 InsetLayout const & il = getLayout();
488 if (il.forceOwnlines())
490 bool needendgroup = false;
491 if (!il.latexname().empty()) {
492 if (il.latextype() == InsetLaTeXType::COMMAND) {
494 // FIXME \protect should only be used for fragile
495 // commands, but we do not provide this information yet.
496 if (hasCProtectContent(runparams.moving_arg)) {
497 if (contains(runparams.active_chars, '^')) {
498 // cprotect relies on ^ being on catcode 7
499 os << "\\begingroup\\catcode`\\^=7";
503 } else if (runparams.moving_arg)
505 os << '\\' << from_utf8(il.latexname());
506 if (!il.latexargs().empty())
507 getArgs(os, runparams);
508 if (!il.latexparam().empty())
509 os << from_utf8(il.latexparam());
511 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
516 if (runparams.lastid != -1)
517 os.texrow().start(runparams.lastid,
519 os << "\\begin{" << from_utf8(il.latexname()) << "}";
520 if (!il.latexargs().empty())
521 getArgs(os, runparams);
522 if (!il.latexparam().empty())
523 os << from_utf8(il.latexparam());
527 if (!il.latexargs().empty())
528 getArgs(os, runparams);
529 if (!il.latexparam().empty())
530 os << from_utf8(il.latexparam());
533 if (!il.leftdelim().empty())
534 os << il.leftdelim();
536 OutputParams rp = runparams;
539 if (il.isNeedProtect())
540 rp.moving_arg = true;
541 if (il.isNeedMBoxProtect())
543 if (!il.passThruChars().empty())
544 rp.pass_thru_chars += il.passThruChars();
545 if (!il.newlineCmd().empty())
546 rp.newlinecmd = il.newlineCmd();
548 rp.par_end = paragraphs().size();
550 // Output the contents of the inset
551 latexParagraphs(buffer(), text_, os, rp);
552 runparams.encoding = rp.encoding;
553 // Pass the post_macros upstream
554 runparams.post_macro = rp.post_macro;
555 // These need to be passed upstream as well
556 runparams.need_maketitle = rp.need_maketitle;
557 runparams.have_maketitle = rp.have_maketitle;
559 if (!il.rightdelim().empty())
560 os << il.rightdelim();
562 if (!il.latexname().empty()) {
563 if (il.latextype() == InsetLaTeXType::COMMAND) {
565 if (!il.postcommandargs().empty())
566 getArgs(os, runparams, true);
569 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
570 // A comment environment doesn't need a % before \n\end
571 if (il.isDisplay() || runparams.inComment)
575 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
577 os.protectSpace(true);
580 if (il.forceOwnlines())
585 int InsetText::plaintext(odocstringstream & os,
586 OutputParams const & runparams, size_t max_length) const
588 ParagraphList::const_iterator beg = paragraphs().begin();
589 ParagraphList::const_iterator end = paragraphs().end();
590 ParagraphList::const_iterator it = beg;
591 bool ref_printed = false;
593 for (; it != end; ++it) {
596 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
599 odocstringstream oss;
600 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
601 docstring const str = oss.str();
603 // FIXME: len is not computed fully correctly; in principle,
604 // we have to count the characters after the last '\n'
606 if (os.str().size() >= max_length)
614 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
616 docbook(xs, rp, WriteEverything);
620 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
622 // Always output all the paragraphs.
623 OutputParams runparams = rp;
624 runparams.par_begin = 0;
625 runparams.par_end = text().paragraphs().size();
628 xs.startDivision(false);
629 docbookParagraphs(text_, buffer(), xs, runparams);
634 InsetLayout const &il = getLayout();
636 // Maybe this is an <info> paragraph that should not be generated
637 // at all (i.e. right now, its place is somewhere else, typically outside
638 // the current paragraph).
639 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
642 // Maybe this inset must be rendered before being output.
643 if (il.docbookrenderasimage()) {
644 docbookRenderAsImage(xs, runparams, opts);
648 // If none of the special cases before apply, output the inset.
649 docbookText(xs, runparams, opts);
653 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
655 LASSERT(getLayout().docbookrenderasimage(), return);
657 // Generate the LaTeX code to compile in order to get the image.
658 // This code actually does the same as an InsetPreview, but without
660 // Also, the image must be generated before the DocBook output is finished,
661 // unlike a preview that is not immediately required for display.
662 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
663 std::string const snippet = support::trim(to_utf8(latex_snippet));
664 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
666 graphics::PreviewLoader* loader = buffer().loader();
667 loader->add(snippet);
668 loader->startLoading(true); // Generate the image and wait until done.
669 graphics::PreviewImage const * img = loader->preview(snippet);
670 LASSERT(img != nullptr, return);
671 support::FileName const & filename = img->filename();
673 // Use a file name that is only determined by the LaTeX code: the name of
674 // the snippet is more or less random (i.e., if the user generates the file
675 // several times, they will have a clutter of preview files).
676 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
677 // the file name will change a lot; two snippets are unlikely to have the
678 // same hash (by design of cryptographic hash functions). Computing a hash
679 // is typically slow, but extremely fast compared to compilation of the
680 // preview and image rendering.
681 std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(snippet)) + "." + filename.extension();
683 // Copy the image into the right folder.
684 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
686 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
687 // Start writing the DocBook code for the image.
688 xs << xml::StartTag("mediaobject")
691 // Output the rendered inset.
692 xs << xml::StartTag("imageobject")
694 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
696 << xml::EndTag("imageobject")
699 // Output the raw content.
700 xs << xml::StartTag("textobject")
702 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
703 docbookText(xs, rp, opts);
704 xs << xml::EndTag("programlisting")
706 << xml::EndTag("textobject")
709 xs << xml::EndTag("mediaobject");
713 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
715 InsetLayout const &il = getLayout();
716 OutputParams runparams = rp;
718 // In some cases, the input parameters must be overridden for outer tags.
719 bool writeOuterTag = opts & WriteOuterTag;
721 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
722 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
723 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
724 auto parSize = (size_t) par.size();
725 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
727 writeOuterTag = !allBibitems;
730 // Detect arguments that should be output before/after the paragraph.
731 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
732 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
733 std::set<InsetArgument const *> prependedArguments;
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->docbookargumentbeforemaintag())
739 prependedArguments.insert(par.getInset(i)->asInsetArgument());
744 std::set<InsetArgument const *> appendedArguments;
745 for (auto const & par : paragraphs()) {
746 for (pos_type i = 0; i < par.size(); ++i) {
747 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
748 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
749 if (arg->docbookargumentaftermaintag())
750 appendedArguments.insert(par.getInset(i)->asInsetArgument());
755 // Start outputting this inset.
756 // - First, wrapper around the inset and its main tag.
758 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
759 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
761 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
762 docstring attrs = docstring();
763 if (!il.docbookattr().empty())
764 attrs += from_ascii(il.docbookattr());
765 if (il.docbooktag() == "link")
766 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
767 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
770 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
771 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
774 // - Think about the arguments before the paragraph.
775 OutputParams np = runparams;
776 np.docbook_in_par = true;
777 for (auto const & arg : prependedArguments)
778 arg->docbook(xs, np);
780 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
781 runparams.docbook_prepended_arguments = std::move(prependedArguments);
782 runparams.docbook_appended_arguments = appendedArguments;
784 // - Deal with the first item.
785 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
787 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
788 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
790 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
791 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
794 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
796 // With respect to XHTML, paragraphs are still allowed here.
797 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
798 runparams.docbook_make_pars = false;
800 runparams.pass_thru = true;
802 // - Write the main content of the inset.
803 xs.startDivision(false);
804 docbookParagraphs(text_, buffer(), xs, runparams);
807 // - Think about the arguments after the paragraph.
808 for (auto const & arg : appendedArguments)
809 arg->docbook(xs, np);
811 // - Close the required tags.
813 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
814 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
816 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
817 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
819 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
820 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
822 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
823 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
825 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
826 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
831 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
833 return insetAsXHTML(xs, runparams, WriteEverything);
838 // There are cases where we may need to close open fonts and such
839 // and then re-open them when we are done. This would be the case, e.g.,
840 // if we were otherwise about to write:
841 // <em>word <div class='foot'>footnote text.</div> emph</em>
842 // The problem isn't so much that the footnote text will get emphasized:
843 // we can handle that with CSS. The problem is that this is invalid XHTML.
844 // One solution would be to make the footnote <span>, but the problem is
845 // completely general, and so we'd have to make absolutely everything into
846 // span. What I think will work is to check if we're about to write "div" and,
847 // if so, try to close fonts, etc.
848 // There are probably limits to how well we can do here, though, and we will
849 // have to rely upon users not putting footnotes inside noun-type insets.
850 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
851 XHTMLOptions opts) const
853 // we will always want to output all our paragraphs when we are
855 OutputParams runparams = rp;
856 runparams.par_begin = 0;
857 runparams.par_end = text().paragraphs().size();
860 xs.startDivision(false);
861 xhtmlParagraphs(text_, buffer(), xs, runparams);
866 InsetLayout const & il = getLayout();
867 if (opts & WriteOuterTag)
868 xs << xml::StartTag(il.htmltag(), il.htmlattr());
870 if ((opts & WriteLabel) && !il.counter().empty()) {
871 BufferParams const & bp = buffer().masterBuffer()->params();
872 Counters & cntrs = bp.documentClass().counters();
873 cntrs.step(il.counter(), OutputUpdate);
874 // FIXME: translate to paragraph language
875 if (!il.htmllabel().empty()) {
876 docstring const lbl =
877 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
878 // FIXME is this check necessary?
880 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
882 xs << xml::EndTag(il.htmllabeltag());
887 if (opts & WriteInnerTag)
888 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
890 // we will eventually lose information about the containing inset
891 if (!allowMultiPar() || opts == JustText)
892 runparams.html_make_pars = false;
894 runparams.pass_thru = true;
896 xs.startDivision(false);
897 xhtmlParagraphs(text_, buffer(), xs, runparams);
900 if (opts & WriteInnerTag)
901 xs << xml::EndTag(il.htmlinnertag());
903 if (opts & WriteOuterTag)
904 xs << xml::EndTag(il.htmltag());
910 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
911 bool const post) const
913 OutputParams runparams = runparams_in;
914 runparams.local_font =
915 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
917 runparams.pass_thru = true;
919 latexArgInsetsForParent(paragraphs(), os, runparams,
920 getLayout().postcommandargs(), "post:");
922 latexArgInsetsForParent(paragraphs(), os, runparams,
923 getLayout().latexargs());
927 void InsetText::cursorPos(BufferView const & bv,
928 CursorSlice const & sl, bool boundary, int & x, int & y) const
930 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
931 y = bv.textMetrics(&text_).cursorY(sl, boundary);
935 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
938 Paragraph & first = paragraphs().front();
939 for (unsigned int i = 0; i < data.length(); ++i)
940 first.insertChar(i, data[i], font, trackChanges);
944 void InsetText::setDrawFrame(bool flag)
950 ColorCode InsetText::frameColor() const
956 void InsetText::setFrameColor(ColorCode col)
962 void InsetText::appendParagraphs(ParagraphList & plist)
964 // There is little we can do here to keep track of changes.
965 // As of 2006/10/20, appendParagraphs is used exclusively by
966 // LyXTabular::setMultiColumn. In this context, the paragraph break
967 // is lost irreversibly and the appended text doesn't really change
969 ParagraphList & pl = paragraphs();
971 ParagraphList::iterator pit = plist.begin();
972 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
974 mergeParagraph(buffer().params(), pl,
975 distance(pl.begin(), ins) - 1);
977 ParagraphList::iterator const pend = plist.end();
978 for (; pit != pend; ++pit)
983 void InsetText::addPreview(DocIterator const & text_inset_pos,
984 graphics::PreviewLoader & loader) const
986 ParagraphList::const_iterator pit = paragraphs().begin();
987 ParagraphList::const_iterator pend = paragraphs().end();
990 DocIterator inset_pos = text_inset_pos;
991 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
993 for (; pit != pend; ++pit, ++pidx) {
994 InsetList::const_iterator it = pit->insetList().begin();
995 InsetList::const_iterator end = pit->insetList().end();
996 inset_pos.pit() = pidx;
997 for (; it != end; ++it) {
998 inset_pos.pos() = it->pos;
999 it->inset->addPreview(inset_pos, loader);
1005 ParagraphList const & InsetText::paragraphs() const
1007 return text_.paragraphs();
1011 ParagraphList & InsetText::paragraphs()
1013 return text_.paragraphs();
1017 bool InsetText::hasCProtectContent(bool fragile) const
1019 fragile |= getLayout().isNeedProtect();
1020 ParagraphList const & pars = paragraphs();
1021 pit_type pend = pit_type(paragraphs().size());
1022 for (pit_type pit = 0; pit != pend; ++pit) {
1023 Paragraph const & par = pars[size_type(pit)];
1024 if (par.needsCProtection(fragile))
1031 bool InsetText::insetAllowed(InsetCode code) const
1034 // Arguments, (plain) quotes and counter insets
1035 // are also allowed in PassThru insets
1041 return !isPassThru();
1046 bool InsetText::allowSpellCheck() const
1048 return getLayout().spellcheck() && !getLayout().isPassThru();
1052 bool InsetText::allowMultiPar() const
1054 return getLayout().isMultiPar();
1058 bool InsetText::forcePlainLayout(idx_type) const
1060 return getLayout().forcePlainLayout();
1064 bool InsetText::allowParagraphCustomization(idx_type) const
1066 return getLayout().allowParagraphCustomization();
1070 bool InsetText::forceLocalFontSwitch() const
1072 return getLayout().forceLocalFontSwitch();
1076 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1078 ParIterator it2 = it;
1080 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1081 if (producesOutput()) {
1082 InsetLayout const & il = getLayout();
1083 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1084 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1086 // LYXERR0("Entering " << name());
1087 cnt.clearLastLayout();
1088 // FIXME cnt.saveLastCounter()?
1090 buffer().updateBuffer(it2, utype, deleted);
1092 // LYXERR0("Exiting " << name());
1093 cnt.restoreLastLayout();
1094 // FIXME cnt.restoreLastCounter()?
1096 // Record if this inset is embedded in a title layout
1097 // This is needed to decide when \maketitle is output.
1098 intitle_context_ = it.paragraph().layout().intitle;
1099 // Also check embedding layouts
1100 size_t const n = it.depth();
1101 for (size_t i = 0; i < n; ++i) {
1102 if (it[i].paragraph().layout().intitle) {
1103 intitle_context_ = true;
1108 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1109 // Note that we do not need to call:
1110 // tclass.counters().clearLastLayout()
1111 // since we are saving and restoring the existing counters, etc.
1112 Counters savecnt = tclass.counters();
1113 tclass.counters().reset();
1114 // we need float information even in note insets (#9760)
1115 tclass.counters().current_float(savecnt.current_float());
1116 tclass.counters().isSubfloat(savecnt.isSubfloat());
1117 buffer().updateBuffer(it2, utype, deleted);
1118 tclass.counters() = move(savecnt);
1123 void InsetText::toString(odocstream & os) const
1125 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1129 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1130 bool const shorten) const
1132 if (!getLayout().isInToc())
1134 text().forOutliner(os, maxlen, shorten);
1138 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1139 UpdateType utype, TocBackend & backend) const
1141 DocIterator dit = cdit;
1142 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1143 iterateForToc(dit, output_active, utype, backend);
1147 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1148 UpdateType utype, TocBackend & backend) const
1150 DocIterator dit = cdit;
1151 // This also ensures that any document has a table of contents
1152 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1154 BufferParams const & bufparams = buffer_->params();
1155 int const min_toclevel = bufparams.documentClass().min_toclevel();
1156 // we really should have done this before we got here, but it
1157 // can't hurt too much to do it again
1158 bool const doing_output = output_active && producesOutput();
1160 // For each paragraph,
1161 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1162 // paragraphs as needed.
1163 // * Traverse its insets and let them add their toc items
1164 // * Compute the main table of contents (this is hardcoded)
1165 // * Add the list of changes
1166 ParagraphList const & pars = paragraphs();
1167 pit_type pend = paragraphs().size();
1168 // Record pairs {start,end} of where a toc item was opened for a paragraph
1169 // and where it must be closed
1170 stack<pair<pit_type, pit_type>> addtotoc_stack;
1172 for (pit_type pit = 0; pit != pend; ++pit) {
1173 Paragraph const & par = pars[pit];
1177 // Custom AddToToc in paragraph layouts (i.e. theorems)
1178 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1180 openAddToTocForParagraph(pit, dit, output_active, backend);
1181 addtotoc_stack.push({pit, end});
1184 // If we find an InsetArgument that is supposed to provide the TOC caption,
1185 // we'll save it for use later.
1186 InsetArgument const * arginset = nullptr;
1187 for (auto const & table : par.insetList()) {
1188 dit.pos() = table.pos;
1189 table.inset->addToToc(dit, doing_output, utype, backend);
1190 if (InsetArgument const * x = table.inset->asInsetArgument())
1191 if (x->isTocCaption())
1195 // End custom AddToToc in paragraph layouts
1196 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1197 // execute the closing function
1198 closeAddToTocForParagraph(addtotoc_stack.top().first,
1199 addtotoc_stack.top().second, backend);
1200 addtotoc_stack.pop();
1203 // now the toc entry for the paragraph in the main table of contents
1204 int const toclevel = text().getTocLevel(pit);
1205 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1206 // insert this into the table of contents
1207 docstring tocstring;
1208 int const length = (doing_output && utype == OutputUpdate) ?
1209 INT_MAX : TOC_ENTRY_LENGTH;
1211 tocstring = par.labelString();
1212 if (!tocstring.empty())
1214 arginset->text().forOutliner(tocstring, length);
1216 par.forOutliner(tocstring, length);
1218 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1219 tocstring, doing_output));
1222 // And now the list of changes.
1223 par.addChangesToToc(dit, buffer(), doing_output, backend);
1228 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1229 DocIterator const & dit,
1231 TocBackend & backend) const
1233 Paragraph const & par = paragraphs()[pit];
1234 TocBuilder & b = backend.builder(par.layout().tocType());
1235 docstring const & label = par.labelString();
1236 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1237 return text().lastInSequence(pit);
1241 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1242 TocBackend & backend) const
1244 Paragraph const & par = paragraphs()[start];
1245 TocBuilder & b = backend.builder(par.layout().tocType());
1246 if (par.layout().isTocCaption()) {
1248 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1249 b.argumentItem(str);
1255 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1257 if (buffer().isClean())
1258 return Inset::notifyCursorLeaves(old, cur);
1260 // find text inset in old cursor
1261 Cursor insetCur = old;
1262 int scriptSlice = insetCur.find(this);
1263 // we can try to continue here. returning true means
1264 // the cursor is "now" invalid. which it was.
1265 LASSERT(scriptSlice != -1, return true);
1266 insetCur.cutOff(scriptSlice);
1267 LASSERT(&insetCur.inset() == this, return true);
1269 // update the old paragraph's words
1270 insetCur.paragraph().updateWords();
1272 return Inset::notifyCursorLeaves(old, cur);
1276 bool InsetText::completionSupported(Cursor const & cur) const
1278 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1279 return text_.completionSupported(cur);
1283 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1285 return completionSupported(cur);
1289 bool InsetText::automaticInlineCompletion() const
1291 return lyxrc.completion_inline_text;
1295 bool InsetText::automaticPopupCompletion() const
1297 return lyxrc.completion_popup_text;
1301 bool InsetText::showCompletionCursor() const
1303 return lyxrc.completion_cursor_text &&
1304 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1308 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1310 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1314 docstring InsetText::completionPrefix(Cursor const & cur) const
1316 if (!completionSupported(cur))
1318 return text_.completionPrefix(cur);
1322 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1325 if (!completionSupported(cur))
1328 return text_.insertCompletion(cur, s, finished);
1332 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1333 Dimension & dim) const
1335 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1336 tm.completionPosAndDim(cur, x, y, dim);
1340 string InsetText::contextMenu(BufferView const &, int, int) const
1342 string context_menu = contextMenuName();
1343 if (context_menu != InsetText::contextMenuName())
1344 context_menu += ";" + InsetText::contextMenuName();
1345 return context_menu;
1349 string InsetText::contextMenuName() const
1351 return "context-edit";
1355 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1357 OutputParams rp(&buffer().params().encoding());
1358 rp.for_tooltip = true;
1359 odocstringstream oss;
1362 ParagraphList::const_iterator beg = paragraphs().begin();
1363 ParagraphList::const_iterator end = paragraphs().end();
1364 ParagraphList::const_iterator it = beg;
1365 bool ref_printed = false;
1367 for (; it != end; ++it) {
1370 if ((*it).isRTL(buffer().params()))
1371 oss << "<div dir=\"rtl\">";
1372 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1373 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1376 docstring str = oss.str();
1378 str += from_ascii("\n\n") + _("[contains tracked changes]");
1379 support::truncateWithEllipsis(str, len);
1384 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1386 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1390 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1392 // Nested cprotect content needs \cprotect
1394 if (producesOutput() && hasCProtectContent(fragile))
1397 // Environments generally need cprotection in fragile context
1398 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1401 if (!getLayout().needsCProtect())
1404 // Environments and "no latex" types (e.g., knitr chunks)
1405 // need cprotection regardless the content
1406 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1409 // If the inset does not produce output (e.g. Note or Branch),
1410 // we can ignore the contained paragraphs
1411 if (!producesOutput())
1414 // Commands need cprotection if they contain specific chars
1415 int const nchars_escape = 9;
1416 static char_type const chars_escape[nchars_escape] = {
1417 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1419 ParagraphList const & pars = paragraphs();
1420 pit_type pend = pit_type(paragraphs().size());
1422 for (pit_type pit = 0; pit != pend; ++pit) {
1423 Paragraph const & par = pars[size_type(pit)];
1424 if (par.needsCProtection(fragile))
1426 docstring const par_str = par.asString();
1427 for (int k = 0; k < nchars_escape; k++) {
1428 if (contains(par_str, chars_escape[k]))