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
337 // This might be needed in general, but we currently
338 // only have evidence for PassThru (latex_font),
341 // assure current cursor font is latex
342 cur.setCurrentFont();
345 case LFUN_INSET_SPLIT:
346 case LFUN_INSET_DISSOLVE: {
347 bool const main_inset = text_.isMainText();
348 bool const target_inset = cmd.argument().empty()
349 || cmd.getArg(0) == insetName(lyxCode());
351 if (!main_inset && target_inset) {
352 UndoGroupHelper ugh(&buffer());
353 // Text::dissolveInset assumes that the cursor
354 // is inside the Inset.
355 if (&cur.inset() != this) {
357 cur.pushBackward(*this);
359 text_.dispatch(cur, cmd);
366 text_.dispatch(cur, cmd);
369 if (!cur.result().dispatched())
370 Inset::doDispatch(cur, cmd);
374 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
375 FuncStatus & status) const
377 switch (cmd.action()) {
378 case LFUN_INSET_SPLIT:
379 case LFUN_INSET_DISSOLVE: {
380 bool const main_inset = text_.isMainText();
381 bool const target_inset = cmd.argument().empty()
382 || cmd.getArg(0) == insetName(lyxCode());
385 status.setEnabled(!main_inset);
389 case LFUN_ARGUMENT_INSERT: {
390 string const arg = cmd.getArg(0);
392 status.setEnabled(false);
395 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
396 return text_.getStatus(cur, cmd, status);
398 Layout::LaTeXArgMap args = getLayout().args();
399 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
400 if (lait != args.end()) {
401 status.setEnabled(true);
402 for (Paragraph const & par : paragraphs())
403 for (auto const & table : par.insetList())
404 if (InsetArgument const * ins = table.inset->asInsetArgument())
405 if (ins->name() == arg) {
406 // we have this already
407 status.setEnabled(false);
411 status.setEnabled(false);
416 // Dispatch only to text_ if the cursor is inside
417 // the text_. It is not for context menus (bug 5797).
419 if (cur.text() == &text_)
420 ret = text_.getStatus(cur, cmd, status);
423 ret = Inset::getStatus(cur, cmd, status);
429 void InsetText::fixParagraphsFont()
431 Font font(inherit_font, buffer().params().language);
432 font.setLanguage(latex_language);
433 ParagraphList::iterator par = paragraphs().begin();
434 ParagraphList::iterator const end = paragraphs().end();
436 if (par->isPassThru())
437 par->resetFonts(font);
438 if (!par->allowParagraphCustomization())
439 par->params().clear();
445 // bool InsetText::isChanged() const
447 // ParagraphList::const_iterator pit = paragraphs().begin();
448 // ParagraphList::const_iterator end = paragraphs().end();
449 // for (; pit != end; ++pit) {
450 // if (pit->isChanged())
457 void InsetText::setChange(Change const & change)
459 ParagraphList::iterator pit = paragraphs().begin();
460 ParagraphList::iterator end = paragraphs().end();
461 for (; pit != end; ++pit) {
462 pit->setChange(change);
467 void InsetText::acceptChanges()
469 text_.acceptChanges();
473 void InsetText::rejectChanges()
475 text_.rejectChanges();
479 void InsetText::validate(LaTeXFeatures & features) const
481 features.useInsetLayout(getLayout());
482 for (Paragraph const & p : paragraphs())
483 p.validate(features);
487 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
489 // This implements the standard way of handling the LaTeX
490 // output of a text inset, either a command or an
491 // environment. Standard collapsible insets should not
492 // redefine this, non-standard ones may call this.
493 InsetLayout const & il = getLayout();
495 if (il.forceOwnlines())
497 bool needendgroup = false;
498 if (!il.latexname().empty()) {
499 if (il.latextype() == InsetLaTeXType::COMMAND) {
501 // FIXME \protect should only be used for fragile
502 // commands, but we do not provide this information yet.
503 if (hasCProtectContent(runparams.moving_arg)) {
504 if (contains(runparams.active_chars, '^')) {
505 // cprotect relies on ^ being on catcode 7
506 os << "\\begingroup\\catcode`\\^=7";
510 } else if (runparams.moving_arg)
512 os << '\\' << from_utf8(il.latexname());
513 if (!il.latexargs().empty())
514 getArgs(os, runparams);
515 if (!il.latexparam().empty())
516 os << from_utf8(il.latexparam());
518 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
523 if (runparams.lastid != -1)
524 os.texrow().start(runparams.lastid,
526 os << "\\begin{" << from_utf8(il.latexname()) << "}";
527 if (!il.latexargs().empty())
528 getArgs(os, runparams);
529 if (!il.latexparam().empty())
530 os << from_utf8(il.latexparam());
534 if (!il.latexargs().empty())
535 getArgs(os, runparams);
536 if (!il.latexparam().empty())
537 os << from_utf8(il.latexparam());
540 if (!il.leftdelim().empty())
541 os << il.leftdelim();
543 OutputParams rp = runparams;
546 if (il.isNeedProtect())
547 rp.moving_arg = true;
548 if (il.isNeedMBoxProtect())
550 if (!il.passThruChars().empty())
551 rp.pass_thru_chars += il.passThruChars();
552 if (!il.newlineCmd().empty())
553 rp.newlinecmd = il.newlineCmd();
555 rp.par_end = paragraphs().size();
557 // Output the contents of the inset
558 latexParagraphs(buffer(), text_, os, rp);
559 runparams.encoding = rp.encoding;
560 // Pass the post_macros upstream
561 runparams.post_macro = rp.post_macro;
562 // These need to be passed upstream as well
563 runparams.need_maketitle = rp.need_maketitle;
564 runparams.have_maketitle = rp.have_maketitle;
566 if (!il.rightdelim().empty())
567 os << il.rightdelim();
569 if (!il.latexname().empty()) {
570 if (il.latextype() == InsetLaTeXType::COMMAND) {
572 if (!il.postcommandargs().empty())
573 getArgs(os, runparams, true);
576 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
577 // A comment environment doesn't need a % before \n\end
578 if (il.isDisplay() || runparams.inComment)
582 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
584 os.protectSpace(true);
587 if (il.forceOwnlines())
592 int InsetText::plaintext(odocstringstream & os,
593 OutputParams const & runparams, size_t max_length) const
595 ParagraphList::const_iterator beg = paragraphs().begin();
596 ParagraphList::const_iterator end = paragraphs().end();
597 ParagraphList::const_iterator it = beg;
598 bool ref_printed = false;
600 for (; it != end; ++it) {
603 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
606 odocstringstream oss;
607 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
608 docstring const str = oss.str();
610 // FIXME: len is not computed fully correctly; in principle,
611 // we have to count the characters after the last '\n'
613 if (os.str().size() >= max_length)
621 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
623 docbook(xs, rp, WriteEverything);
627 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
629 // Always output all the paragraphs.
630 OutputParams runparams = rp;
631 runparams.par_begin = 0;
632 runparams.par_end = text().paragraphs().size();
635 xs.startDivision(false);
636 docbookParagraphs(text_, buffer(), xs, runparams);
641 InsetLayout const &il = getLayout();
643 // Maybe this is an <info> paragraph that should not be generated
644 // at all (i.e. right now, its place is somewhere else, typically outside
645 // the current paragraph).
646 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
649 // Maybe this inset must be rendered before being output.
650 if (il.docbookrenderasimage()) {
651 docbookRenderAsImage(xs, runparams, opts);
655 // If none of the special cases before apply, output the inset.
656 docbookText(xs, runparams, opts);
660 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
662 LASSERT(getLayout().docbookrenderasimage(), return);
664 // Generate the LaTeX code to compile in order to get the image.
665 // This code actually does the same as an InsetPreview, but without
667 // Also, the image must be generated before the DocBook output is finished,
668 // unlike a preview that is not immediately required for display.
669 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
670 docstring const snippet = support::trim(latex_snippet);
671 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
673 graphics::PreviewLoader* loader = buffer().loader();
674 // This should be OK because we are exporting
675 LASSERT(loader != nullptr, return);
676 loader->add(snippet);
677 loader->startLoading(true); // Generate the image and wait until done.
678 graphics::PreviewImage const * img = loader->preview(snippet);
679 LASSERT(img != nullptr, return);
680 support::FileName const & filename = img->filename();
682 // Use a file name that is only determined by the LaTeX code: the name of
683 // the snippet is more or less random (i.e., if the user generates the file
684 // several times, they will have a clutter of preview files).
685 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
686 // the file name will change a lot; two snippets are unlikely to have the
687 // same hash (by design of cryptographic hash functions). Computing a hash
688 // is typically slow, but extremely fast compared to compilation of the
689 // preview and image rendering.
690 std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(to_utf8(snippet))) + "." + filename.extension();
692 // Copy the image into the right folder.
693 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
695 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
696 // Start writing the DocBook code for the image.
697 xs << xml::StartTag("mediaobject")
700 // Output the rendered inset.
701 xs << xml::StartTag("imageobject")
703 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
705 << xml::EndTag("imageobject")
708 // Output the raw content.
709 xs << xml::StartTag("textobject")
711 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
712 docbookText(xs, rp, opts);
713 xs << xml::EndTag("programlisting")
715 << xml::EndTag("textobject")
718 xs << xml::EndTag("mediaobject");
722 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
724 InsetLayout const &il = getLayout();
725 OutputParams runparams = rp;
727 // In some cases, the input parameters must be overridden for outer tags.
728 bool writeOuterTag = opts & WriteOuterTag;
730 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
731 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
732 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
733 auto parSize = (size_t) par.size();
734 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
736 writeOuterTag = !allBibitems;
739 // Detect arguments that should be output before/after the paragraph.
740 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
741 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
742 std::set<InsetArgument const *> prependedArguments;
743 for (auto const & par : paragraphs()) {
744 for (pos_type i = 0; i < par.size(); ++i) {
745 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
746 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
747 if (arg->docbookargumentbeforemaintag())
748 prependedArguments.insert(par.getInset(i)->asInsetArgument());
753 std::set<InsetArgument const *> appendedArguments;
754 for (auto const & par : paragraphs()) {
755 for (pos_type i = 0; i < par.size(); ++i) {
756 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
757 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
758 if (arg->docbookargumentaftermaintag())
759 appendedArguments.insert(par.getInset(i)->asInsetArgument());
764 // Start outputting this inset.
765 // - First, wrapper around the inset and its main tag.
767 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
768 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
770 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
771 docstring attrs = docstring();
772 if (!il.docbookattr().empty())
773 attrs += from_ascii(il.docbookattr());
774 if (il.docbooktag() == "link")
775 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
776 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
779 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
780 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
783 // - Think about the arguments before the paragraph.
784 OutputParams np = runparams;
785 np.docbook_in_par = true;
786 for (auto const & arg : prependedArguments)
787 arg->docbook(xs, np);
789 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
790 runparams.docbook_prepended_arguments = std::move(prependedArguments);
791 runparams.docbook_appended_arguments = appendedArguments;
793 // - Deal with the first item.
794 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
796 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
797 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
799 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
800 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
803 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
805 // With respect to XHTML, paragraphs are still allowed here.
806 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
807 runparams.docbook_make_pars = false;
809 runparams.pass_thru = true;
811 // - Write the main content of the inset.
812 xs.startDivision(false);
813 docbookParagraphs(text_, buffer(), xs, runparams);
816 // - Think about the arguments after the paragraph.
817 for (auto const & arg : appendedArguments)
818 arg->docbook(xs, np);
820 // - Close the required tags.
822 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
823 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
825 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
826 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
828 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
829 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
831 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
832 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
834 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
835 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
840 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
842 return insetAsXHTML(xs, runparams, WriteEverything);
847 // There are cases where we may need to close open fonts and such
848 // and then re-open them when we are done. This would be the case, e.g.,
849 // if we were otherwise about to write:
850 // <em>word <div class='foot'>footnote text.</div> emph</em>
851 // The problem isn't so much that the footnote text will get emphasized:
852 // we can handle that with CSS. The problem is that this is invalid XHTML.
853 // One solution would be to make the footnote <span>, but the problem is
854 // completely general, and so we'd have to make absolutely everything into
855 // span. What I think will work is to check if we're about to write "div" and,
856 // if so, try to close fonts, etc.
857 // There are probably limits to how well we can do here, though, and we will
858 // have to rely upon users not putting footnotes inside noun-type insets.
859 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
860 XHTMLOptions opts) const
862 // we will always want to output all our paragraphs when we are
864 OutputParams runparams = rp;
865 runparams.par_begin = 0;
866 runparams.par_end = text().paragraphs().size();
869 xs.startDivision(false);
870 xhtmlParagraphs(text_, buffer(), xs, runparams);
875 InsetLayout const & il = getLayout();
876 if (opts & WriteOuterTag)
877 xs << xml::StartTag(il.htmltag(), il.htmlGetAttrString());
879 if ((opts & WriteLabel) && !il.counter().empty()) {
880 BufferParams const & bp = buffer().masterBuffer()->params();
881 Counters & cntrs = bp.documentClass().counters();
882 cntrs.step(il.counter(), OutputUpdate);
883 // FIXME: translate to paragraph language
884 if (!il.htmllabel().empty()) {
885 docstring const lbl =
886 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
887 // FIXME is this check necessary?
889 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
891 xs << xml::EndTag(il.htmllabeltag());
896 if (opts & WriteInnerTag)
897 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
899 // we will eventually lose information about the containing inset
900 if (!allowMultiPar() || opts == JustText)
901 runparams.html_make_pars = false;
903 runparams.pass_thru = true;
905 xs.startDivision(false);
906 xhtmlParagraphs(text_, buffer(), xs, runparams);
909 if (opts & WriteInnerTag)
910 xs << xml::EndTag(il.htmlinnertag());
912 if (opts & WriteOuterTag)
913 xs << xml::EndTag(il.htmltag());
919 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
920 bool const post) const
922 OutputParams runparams = runparams_in;
923 runparams.local_font =
924 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
926 runparams.pass_thru = true;
928 latexArgInsetsForParent(paragraphs(), os, runparams,
929 getLayout().postcommandargs(), "post:");
931 latexArgInsetsForParent(paragraphs(), os, runparams,
932 getLayout().latexargs());
936 void InsetText::cursorPos(BufferView const & bv,
937 CursorSlice const & sl, bool boundary, int & x, int & y) const
939 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
940 y = bv.textMetrics(&text_).cursorY(sl, boundary);
944 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
947 Paragraph & first = paragraphs().front();
948 for (unsigned int i = 0; i < data.length(); ++i)
949 first.insertChar(i, data[i], font, trackChanges);
953 void InsetText::setDrawFrame(bool flag)
959 ColorCode InsetText::frameColor() const
965 void InsetText::setFrameColor(ColorCode col)
971 void InsetText::appendParagraphs(ParagraphList & plist)
973 // There is little we can do here to keep track of changes.
974 // As of 2006/10/20, appendParagraphs is used exclusively by
975 // LyXTabular::setMultiColumn. In this context, the paragraph break
976 // is lost irreversibly and the appended text doesn't really change
978 ParagraphList & pl = paragraphs();
980 ParagraphList::iterator pit = plist.begin();
981 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
983 mergeParagraph(buffer().params(), pl,
984 distance(pl.begin(), ins) - 1);
986 ParagraphList::iterator const pend = plist.end();
987 for (; pit != pend; ++pit)
992 void InsetText::addPreview(DocIterator const & text_inset_pos,
993 graphics::PreviewLoader & loader) const
995 ParagraphList::const_iterator pit = paragraphs().begin();
996 ParagraphList::const_iterator pend = paragraphs().end();
999 DocIterator inset_pos = text_inset_pos;
1000 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
1002 for (; pit != pend; ++pit, ++pidx) {
1003 InsetList::const_iterator it = pit->insetList().begin();
1004 InsetList::const_iterator end = pit->insetList().end();
1005 inset_pos.pit() = pidx;
1006 for (; it != end; ++it) {
1007 inset_pos.pos() = it->pos;
1008 it->inset->addPreview(inset_pos, loader);
1014 ParagraphList const & InsetText::paragraphs() const
1016 return text_.paragraphs();
1020 ParagraphList & InsetText::paragraphs()
1022 return text_.paragraphs();
1026 bool InsetText::hasCProtectContent(bool fragile) const
1028 fragile |= getLayout().isNeedProtect();
1029 ParagraphList const & pars = paragraphs();
1030 pit_type pend = pit_type(paragraphs().size());
1031 for (pit_type pit = 0; pit != pend; ++pit) {
1032 Paragraph const & par = pars[size_type(pit)];
1033 if (par.needsCProtection(fragile))
1040 bool InsetText::insetAllowed(InsetCode code) const
1043 // Arguments, (plain) quotes and counter insets
1044 // are also allowed in PassThru insets
1049 // These are only allowed in index insets
1050 case INDEXMACRO_CODE:
1051 case INDEXMACRO_SORTKEY_CODE:
1054 return !isPassThru();
1059 bool InsetText::allowSpellCheck() const
1061 return getLayout().spellcheck() && !getLayout().isPassThru();
1065 bool InsetText::allowMultiPar() const
1067 return getLayout().isMultiPar();
1071 bool InsetText::forcePlainLayout(idx_type) const
1073 return getLayout().forcePlainLayout();
1077 bool InsetText::allowParagraphCustomization(idx_type) const
1079 return getLayout().allowParagraphCustomization();
1083 bool InsetText::forceLocalFontSwitch() const
1085 return getLayout().forceLocalFontSwitch();
1089 void InsetText::checkIntitleContext(ParIterator const & it)
1091 intitle_context_ = it.paragraph().layout().intitle;
1092 // Also check embedding layouts
1093 size_t const n = it.depth();
1094 for (size_t i = 0; i < n; ++i) {
1095 if (it[i].paragraph().layout().intitle) {
1096 intitle_context_ = true;
1103 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1105 ParIterator it2 = it;
1107 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1108 if (producesOutput()) {
1109 InsetLayout const & il = getLayout();
1110 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1111 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1113 // LYXERR0("Entering " << name());
1114 cnt.clearLastLayout();
1115 // FIXME cnt.saveLastCounter()?
1117 buffer().updateBuffer(it2, utype, deleted);
1119 // LYXERR0("Exiting " << name());
1120 cnt.restoreLastLayout();
1121 // FIXME cnt.restoreLastCounter()?
1123 checkIntitleContext(it);
1125 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1126 // Note that we do not need to call:
1127 // tclass.counters().clearLastLayout()
1128 // since we are saving and restoring the existing counters, etc.
1129 Counters savecnt = tclass.counters();
1130 tclass.counters().reset();
1131 // we need float information even in note insets (#9760)
1132 tclass.counters().current_float(savecnt.current_float());
1133 tclass.counters().isSubfloat(savecnt.isSubfloat());
1134 buffer().updateBuffer(it2, utype, deleted);
1135 tclass.counters() = std::move(savecnt);
1140 void InsetText::toString(odocstream & os) const
1142 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1146 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1147 bool const shorten) const
1149 if (!getLayout().isInToc())
1151 text().forOutliner(os, maxlen, shorten);
1155 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1156 UpdateType utype, TocBackend & backend) const
1158 DocIterator dit = cdit;
1159 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1160 iterateForToc(dit, output_active, utype, backend);
1164 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1165 UpdateType utype, TocBackend & backend) const
1167 DocIterator dit = cdit;
1168 // This also ensures that any document has a table of contents
1169 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1171 BufferParams const & bufparams = buffer_->params();
1172 int const min_toclevel = bufparams.documentClass().min_toclevel();
1173 // we really should have done this before we got here, but it
1174 // can't hurt too much to do it again
1175 bool const doing_output = output_active && producesOutput();
1177 // For each paragraph,
1178 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1179 // paragraphs as needed.
1180 // * Traverse its insets and let them add their toc items
1181 // * Compute the main table of contents (this is hardcoded)
1182 // * Add the list of changes
1183 ParagraphList const & pars = paragraphs();
1184 pit_type pend = paragraphs().size();
1185 // Record pairs {start,end} of where a toc item was opened for a paragraph
1186 // and where it must be closed
1187 stack<pair<pit_type, pit_type>> addtotoc_stack;
1189 for (pit_type pit = 0; pit != pend; ++pit) {
1190 Paragraph const & par = pars[pit];
1194 // Custom AddToToc in paragraph layouts (i.e. theorems)
1195 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1197 openAddToTocForParagraph(pit, dit, output_active, backend);
1198 addtotoc_stack.push({pit, end});
1201 // If we find an InsetArgument that is supposed to provide the TOC caption,
1202 // we'll save it for use later.
1203 InsetArgument const * arginset = nullptr;
1204 for (auto const & elem : par.insetList()) {
1205 dit.pos() = elem.pos;
1206 elem.inset->addToToc(dit, doing_output, utype, backend);
1207 if (InsetArgument const * x = elem.inset->asInsetArgument())
1208 if (x->isTocCaption())
1212 // End custom AddToToc in paragraph layouts
1213 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1214 // execute the closing function
1215 closeAddToTocForParagraph(addtotoc_stack.top().first,
1216 addtotoc_stack.top().second, backend);
1217 addtotoc_stack.pop();
1220 // now the toc entry for the paragraph in the main table of contents
1221 int const toclevel = text().getTocLevel(pit);
1222 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1223 // insert this into the table of contents
1224 docstring tocstring;
1225 int const length = (doing_output && utype == OutputUpdate) ?
1226 INT_MAX : TOC_ENTRY_LENGTH;
1228 tocstring = par.labelString();
1229 if (!tocstring.empty())
1231 arginset->text().forOutliner(tocstring, length);
1233 par.forOutliner(tocstring, length);
1235 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1236 tocstring, doing_output));
1239 // And now the list of changes.
1240 par.addChangesToToc(dit, buffer(), doing_output, backend);
1245 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1246 DocIterator const & dit,
1248 TocBackend & backend) const
1250 Paragraph const & par = paragraphs()[pit];
1251 TocBuilder & b = backend.builder(par.layout().tocType());
1252 docstring const & label = par.labelString();
1253 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1254 return text().lastInSequence(pit);
1258 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1259 TocBackend & backend) const
1261 Paragraph const & par = paragraphs()[start];
1262 TocBuilder & b = backend.builder(par.layout().tocType());
1263 if (par.layout().isTocCaption()) {
1265 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1266 b.argumentItem(str);
1272 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1274 if (buffer().isClean())
1275 return Inset::notifyCursorLeaves(old, cur);
1277 // find text inset in old cursor
1278 Cursor insetCur = old;
1279 int scriptSlice = insetCur.find(this);
1280 // we can try to continue here. returning true means
1281 // the cursor is "now" invalid. which it was.
1282 LASSERT(scriptSlice != -1, return true);
1283 insetCur.cutOff(scriptSlice);
1284 LASSERT(&insetCur.inset() == this, return true);
1286 // update the old paragraph's words
1287 insetCur.paragraph().updateWords();
1289 return Inset::notifyCursorLeaves(old, cur);
1293 bool InsetText::completionSupported(Cursor const & cur) const
1295 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1296 return text_.completionSupported(cur);
1300 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1302 return completionSupported(cur);
1306 bool InsetText::automaticInlineCompletion() const
1308 return lyxrc.completion_inline_text;
1312 bool InsetText::automaticPopupCompletion() const
1314 return lyxrc.completion_popup_text;
1318 bool InsetText::showCompletionCursor() const
1320 return lyxrc.completion_cursor_text &&
1321 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1325 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1327 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1331 docstring InsetText::completionPrefix(Cursor const & cur) const
1333 if (!completionSupported(cur))
1335 return text_.completionPrefix(cur);
1339 bool InsetText::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1341 if (!completionSupported(cur))
1344 return text_.insertCompletion(cur, s);
1348 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1349 Dimension & dim) const
1351 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1352 tm.completionPosAndDim(cur, x, y, dim);
1356 string InsetText::contextMenu(BufferView const &, int, int) const
1358 string context_menu = contextMenuName();
1359 if (context_menu != InsetText::contextMenuName())
1360 context_menu += ";" + InsetText::contextMenuName();
1361 return context_menu;
1365 string InsetText::contextMenuName() const
1367 return "context-edit";
1371 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1373 OutputParams rp(&buffer().params().encoding());
1374 rp.for_tooltip = true;
1375 odocstringstream oss;
1378 ParagraphList::const_iterator beg = paragraphs().begin();
1379 ParagraphList::const_iterator end = paragraphs().end();
1380 ParagraphList::const_iterator it = beg;
1381 bool ref_printed = false;
1383 for (; it != end; ++it) {
1386 if ((*it).isRTL(buffer().params()))
1387 oss << "<div dir=\"rtl\">";
1388 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1389 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1392 docstring str = oss.str();
1394 str += from_ascii("\n\n") + _("[contains tracked changes]");
1395 support::truncateWithEllipsis(str, len);
1400 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1402 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1406 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1408 // Nested cprotect content needs \cprotect
1410 if (producesOutput() && hasCProtectContent(fragile))
1413 // Environments generally need cprotection in fragile context
1414 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1417 if (!getLayout().needsCProtect())
1420 // Environments and "no latex" types (e.g., knitr chunks)
1421 // need cprotection regardless the content
1422 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1425 // If the inset does not produce output (e.g. Note or Branch),
1426 // we can ignore the contained paragraphs
1427 if (!producesOutput())
1430 // Commands need cprotection if they contain specific chars
1431 int const nchars_escape = 9;
1432 static char_type const chars_escape[nchars_escape] = {
1433 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1435 ParagraphList const & pars = paragraphs();
1436 pit_type pend = pit_type(paragraphs().size());
1438 for (pit_type pit = 0; pit != pend; ++pit) {
1439 Paragraph const & par = pars[size_type(pit)];
1440 if (par.needsCProtection(fragile))
1442 docstring const par_str = par.asString();
1443 for (int k = 0; k < nchars_escape; k++) {
1444 if (!maintext && contains(par_str, chars_escape[k]))