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"
42 #include "support/Lexer.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 (!il.noCProtect() && !runparams.no_cprotect && 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.noPassThruChars().empty())
553 rp.no_pass_thru_chars += il.noPassThruChars();
555 rp.no_cprotect = true;
556 if (!il.newlineCmd().empty())
557 rp.newlinecmd = il.newlineCmd();
559 rp.par_end = paragraphs().size();
561 // Output the contents of the inset
562 latexParagraphs(buffer(), text_, os, rp);
563 runparams.encoding = rp.encoding;
564 // Pass the post_macros upstream
565 runparams.post_macro = rp.post_macro;
566 // These need to be passed upstream as well
567 runparams.need_maketitle = rp.need_maketitle;
568 runparams.have_maketitle = rp.have_maketitle;
570 if (!il.rightdelim().empty())
571 os << il.rightdelim();
573 if (!il.latexname().empty()) {
574 if (il.latextype() == InsetLaTeXType::COMMAND) {
576 if (!il.postcommandargs().empty())
577 getArgs(os, runparams, true);
580 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
581 // A comment environment doesn't need a % before \n\end
582 if (il.isDisplay() || runparams.inComment)
586 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
588 os.protectSpace(true);
591 if (il.forceOwnlines())
596 int InsetText::plaintext(odocstringstream & os,
597 OutputParams const & runparams, size_t max_length) const
599 ParagraphList::const_iterator beg = paragraphs().begin();
600 ParagraphList::const_iterator end = paragraphs().end();
601 ParagraphList::const_iterator it = beg;
602 bool ref_printed = false;
604 for (; it != end; ++it) {
607 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
610 odocstringstream oss;
611 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
612 docstring const str = oss.str();
614 // FIXME: len is not computed fully correctly; in principle,
615 // we have to count the characters after the last '\n'
617 if (os.str().size() >= max_length)
625 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
627 docbook(xs, rp, WriteEverything);
631 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
633 // Always output all the paragraphs.
634 OutputParams runparams = rp;
635 runparams.par_begin = 0;
636 runparams.par_end = text().paragraphs().size();
639 xs.startDivision(false);
640 docbookParagraphs(text_, buffer(), xs, runparams);
645 InsetLayout const &il = getLayout();
647 // Maybe this is an <info> paragraph that should not be generated
648 // at all (i.e. right now, its place is somewhere else, typically outside
649 // the current paragraph).
650 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
653 // Maybe this inset must be rendered before being output.
654 if (il.docbookrenderasimage()) {
655 docbookRenderAsImage(xs, runparams, opts);
659 // If none of the special cases before apply, output the inset.
660 docbookText(xs, runparams, opts);
664 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
666 LASSERT(getLayout().docbookrenderasimage(), return);
668 // Generate the LaTeX code to compile in order to get the image.
669 // This code actually does the same as an InsetPreview, but without
671 // Also, the image must be generated before the DocBook output is finished,
672 // unlike a preview that is not immediately required for display.
673 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
674 docstring const snippet = support::trim(latex_snippet);
675 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
677 graphics::PreviewLoader* loader = buffer().loader();
678 // This should be OK because we are exporting
679 LASSERT(loader != nullptr, return);
680 loader->add(snippet);
681 loader->startLoading(true); // Generate the image and wait until done.
682 graphics::PreviewImage const * img = loader->preview(snippet);
683 LASSERT(img != nullptr, return);
684 support::FileName const & filename = img->filename();
686 // Use a file name that is only determined by the LaTeX code: the name of
687 // the snippet is more or less random (i.e., if the user generates the file
688 // several times, they will have a clutter of preview files).
689 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
690 // the file name will change a lot; two snippets are unlikely to have the
691 // same hash (by design of cryptographic hash functions). Computing a hash
692 // is typically slow, but extremely fast compared to compilation of the
693 // preview and image rendering.
694 std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(to_utf8(snippet))) + "." + filename.extension();
696 // Copy the image into the right folder.
697 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
699 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
700 // Start writing the DocBook code for the image.
701 xs << xml::StartTag("mediaobject")
704 // Output the rendered inset.
705 xs << xml::StartTag("imageobject")
707 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
709 << xml::EndTag("imageobject")
712 // Output the raw content.
713 xs << xml::StartTag("textobject")
715 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
716 docbookText(xs, rp, opts);
717 xs << xml::EndTag("programlisting")
719 << xml::EndTag("textobject")
722 xs << xml::EndTag("mediaobject");
726 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
728 InsetLayout const &il = getLayout();
729 OutputParams runparams = rp;
731 // In some cases, the input parameters must be overridden for outer tags.
732 bool writeOuterTag = opts & WriteOuterTag;
734 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
735 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
736 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
737 auto parSize = (size_t) par.size();
738 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
740 writeOuterTag = !allBibitems;
743 // Detect arguments that should be output before/after the paragraph.
744 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
745 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
746 std::set<InsetArgument const *> prependedArguments;
747 for (auto const & par : paragraphs()) {
748 for (pos_type i = 0; i < par.size(); ++i) {
749 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
750 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
751 if (arg->docbookargumentbeforemaintag())
752 prependedArguments.insert(par.getInset(i)->asInsetArgument());
757 std::set<InsetArgument const *> appendedArguments;
758 for (auto const & par : paragraphs()) {
759 for (pos_type i = 0; i < par.size(); ++i) {
760 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
761 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
762 if (arg->docbookargumentaftermaintag())
763 appendedArguments.insert(par.getInset(i)->asInsetArgument());
768 // Start outputting this inset.
769 // - First, wrapper around the inset and its main tag.
771 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
772 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
774 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
775 docstring attrs = docstring();
776 if (!il.docbookattr().empty())
777 attrs += from_ascii(il.docbookattr());
778 if (il.docbooktag() == "link")
779 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
780 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
783 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
784 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
787 // - Think about the arguments before the paragraph.
788 OutputParams np = runparams;
789 np.docbook_in_par = true;
790 for (auto const & arg : prependedArguments)
791 arg->docbook(xs, np);
793 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
794 runparams.docbook_prepended_arguments = std::move(prependedArguments);
795 runparams.docbook_appended_arguments = appendedArguments;
797 // - Deal with the first item.
798 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
800 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
801 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
803 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
804 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
807 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
809 // With respect to XHTML, paragraphs are still allowed here.
810 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
811 runparams.docbook_make_pars = false;
813 runparams.pass_thru = true;
815 // - Write the main content of the inset.
816 xs.startDivision(false);
817 docbookParagraphs(text_, buffer(), xs, runparams);
820 // - Think about the arguments after the paragraph.
821 for (auto const & arg : appendedArguments)
822 arg->docbook(xs, np);
824 // - Close the required tags.
826 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
827 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
829 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
830 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
832 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
833 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
835 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
836 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
838 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
839 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
844 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
846 return insetAsXHTML(xs, runparams, WriteEverything);
851 // There are cases where we may need to close open fonts and such
852 // and then re-open them when we are done. This would be the case, e.g.,
853 // if we were otherwise about to write:
854 // <em>word <div class='foot'>footnote text.</div> emph</em>
855 // The problem isn't so much that the footnote text will get emphasized:
856 // we can handle that with CSS. The problem is that this is invalid XHTML.
857 // One solution would be to make the footnote <span>, but the problem is
858 // completely general, and so we'd have to make absolutely everything into
859 // span. What I think will work is to check if we're about to write "div" and,
860 // if so, try to close fonts, etc.
861 // There are probably limits to how well we can do here, though, and we will
862 // have to rely upon users not putting footnotes inside noun-type insets.
863 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
864 XHTMLOptions opts) const
866 // we will always want to output all our paragraphs when we are
868 OutputParams runparams = rp;
869 runparams.par_begin = 0;
870 runparams.par_end = text().paragraphs().size();
873 xs.startDivision(false);
874 xhtmlParagraphs(text_, buffer(), xs, runparams);
879 InsetLayout const & il = getLayout();
880 if (opts & WriteOuterTag)
881 xs << xml::StartTag(il.htmltag(), il.htmlGetAttrString());
883 if ((opts & WriteLabel) && !il.counter().empty()) {
884 BufferParams const & bp = buffer().masterBuffer()->params();
885 Counters & cntrs = bp.documentClass().counters();
886 cntrs.step(il.counter(), OutputUpdate);
887 // FIXME: translate to paragraph language
888 if (!il.htmllabel().empty()) {
889 docstring const lbl =
890 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
891 // FIXME is this check necessary?
893 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
895 xs << xml::EndTag(il.htmllabeltag());
900 if (opts & WriteInnerTag)
901 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
903 // we will eventually lose information about the containing inset
904 if (!allowMultiPar() || opts == JustText)
905 runparams.html_make_pars = false;
907 runparams.pass_thru = true;
909 xs.startDivision(false);
910 xhtmlParagraphs(text_, buffer(), xs, runparams);
913 if (opts & WriteInnerTag)
914 xs << xml::EndTag(il.htmlinnertag());
916 if (opts & WriteOuterTag)
917 xs << xml::EndTag(il.htmltag());
923 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
924 bool const post) const
926 OutputParams runparams = runparams_in;
927 runparams.local_font =
928 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
930 runparams.pass_thru = true;
932 latexArgInsetsForParent(paragraphs(), os, runparams,
933 getLayout().postcommandargs(), "post:");
935 latexArgInsetsForParent(paragraphs(), os, runparams,
936 getLayout().latexargs());
940 void InsetText::cursorPos(BufferView const & bv,
941 CursorSlice const & sl, bool boundary, int & x, int & y) const
943 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
944 y = bv.textMetrics(&text_).cursorY(sl, boundary);
948 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
951 Paragraph & first = paragraphs().front();
952 for (unsigned int i = 0; i < data.length(); ++i)
953 first.insertChar(i, data[i], font, trackChanges);
957 void InsetText::setDrawFrame(bool flag)
963 ColorCode InsetText::frameColor() const
969 void InsetText::setFrameColor(ColorCode col)
975 void InsetText::appendParagraphs(ParagraphList & plist)
977 // There is little we can do here to keep track of changes.
978 // As of 2006/10/20, appendParagraphs is used exclusively by
979 // LyXTabular::setMultiColumn. In this context, the paragraph break
980 // is lost irreversibly and the appended text doesn't really change
982 ParagraphList & pl = paragraphs();
984 ParagraphList::iterator pit = plist.begin();
985 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
987 mergeParagraph(buffer().params(), pl,
988 distance(pl.begin(), ins) - 1);
990 ParagraphList::iterator const pend = plist.end();
991 for (; pit != pend; ++pit)
996 void InsetText::addPreview(DocIterator const & text_inset_pos,
997 graphics::PreviewLoader & loader) const
999 ParagraphList::const_iterator pit = paragraphs().begin();
1000 ParagraphList::const_iterator pend = paragraphs().end();
1003 DocIterator inset_pos = text_inset_pos;
1004 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
1006 for (; pit != pend; ++pit, ++pidx) {
1007 InsetList::const_iterator it = pit->insetList().begin();
1008 InsetList::const_iterator end = pit->insetList().end();
1009 inset_pos.pit() = pidx;
1010 for (; it != end; ++it) {
1011 inset_pos.pos() = it->pos;
1012 it->inset->addPreview(inset_pos, loader);
1018 ParagraphList const & InsetText::paragraphs() const
1020 return text_.paragraphs();
1024 ParagraphList & InsetText::paragraphs()
1026 return text_.paragraphs();
1030 bool InsetText::hasCProtectContent(bool fragile) const
1032 fragile |= getLayout().isNeedProtect();
1033 ParagraphList const & pars = paragraphs();
1034 pit_type pend = pit_type(paragraphs().size());
1035 for (pit_type pit = 0; pit != pend; ++pit) {
1036 Paragraph const & par = pars[size_type(pit)];
1037 if (par.needsCProtection(fragile))
1044 bool InsetText::insetAllowed(InsetCode code) const
1047 // Arguments, (plain) quotes and counter insets
1048 // are also allowed in PassThru insets
1053 // These are only allowed in index insets
1054 case INDEXMACRO_CODE:
1055 case INDEXMACRO_SORTKEY_CODE:
1058 return !isPassThru();
1063 bool InsetText::allowSpellCheck() const
1065 return getLayout().spellcheck() && !getLayout().isPassThru();
1069 bool InsetText::allowMultiPar() const
1071 return getLayout().isMultiPar();
1075 bool InsetText::forcePlainLayout(idx_type) const
1077 return getLayout().forcePlainLayout();
1081 bool InsetText::allowParagraphCustomization(idx_type) const
1083 return getLayout().allowParagraphCustomization();
1087 bool InsetText::forceLocalFontSwitch() const
1089 return getLayout().forceLocalFontSwitch();
1093 void InsetText::checkIntitleContext(ParIterator const & it)
1095 intitle_context_ = it.paragraph().layout().intitle;
1096 // Also check embedding layouts
1097 size_t const n = it.depth();
1098 for (size_t i = 0; i < n; ++i) {
1099 if (it[i].paragraph().layout().intitle) {
1100 intitle_context_ = true;
1107 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1109 ParIterator it2 = it;
1111 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1112 if (producesOutput()) {
1113 InsetLayout const & il = getLayout();
1114 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1115 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1117 // LYXERR0("Entering " << name());
1118 cnt.clearLastLayout();
1119 // FIXME cnt.saveLastCounter()?
1121 buffer().updateBuffer(it2, utype, deleted);
1123 // LYXERR0("Exiting " << name());
1124 cnt.restoreLastLayout();
1125 // FIXME cnt.restoreLastCounter()?
1127 checkIntitleContext(it);
1129 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1130 // Note that we do not need to call:
1131 // tclass.counters().clearLastLayout()
1132 // since we are saving and restoring the existing counters, etc.
1133 Counters savecnt = tclass.counters();
1134 tclass.counters().reset();
1135 // we need float information even in note insets (#9760)
1136 tclass.counters().current_float(savecnt.current_float());
1137 tclass.counters().isSubfloat(savecnt.isSubfloat());
1138 buffer().updateBuffer(it2, utype, deleted);
1139 tclass.counters() = std::move(savecnt);
1144 void InsetText::toString(odocstream & os) const
1146 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1150 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1151 bool const shorten) const
1153 if (!getLayout().isInToc())
1155 text().forOutliner(os, maxlen, shorten);
1159 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1160 UpdateType utype, TocBackend & backend) const
1162 DocIterator dit = cdit;
1163 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1164 iterateForToc(dit, output_active, utype, backend);
1168 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1169 UpdateType utype, TocBackend & backend) const
1171 DocIterator dit = cdit;
1172 // This also ensures that any document has a table of contents
1173 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1175 BufferParams const & bufparams = buffer_->params();
1176 int const min_toclevel = bufparams.documentClass().min_toclevel();
1177 // we really should have done this before we got here, but it
1178 // can't hurt too much to do it again
1179 bool const doing_output = output_active && producesOutput();
1181 // For each paragraph,
1182 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1183 // paragraphs as needed.
1184 // * Traverse its insets and let them add their toc items
1185 // * Compute the main table of contents (this is hardcoded)
1186 // * Add the list of changes
1187 ParagraphList const & pars = paragraphs();
1188 pit_type pend = paragraphs().size();
1189 // Record pairs {start,end} of where a toc item was opened for a paragraph
1190 // and where it must be closed
1191 stack<pair<pit_type, pit_type>> addtotoc_stack;
1193 for (pit_type pit = 0; pit != pend; ++pit) {
1194 Paragraph const & par = pars[pit];
1198 // Custom AddToToc in paragraph layouts (i.e. theorems)
1199 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1201 openAddToTocForParagraph(pit, dit, output_active, backend);
1202 addtotoc_stack.push({pit, end});
1205 // If we find an InsetArgument that is supposed to provide the TOC caption,
1206 // we'll save it for use later.
1207 InsetArgument const * arginset = nullptr;
1208 for (auto const & elem : par.insetList()) {
1209 dit.pos() = elem.pos;
1210 elem.inset->addToToc(dit, doing_output, utype, backend);
1211 if (InsetArgument const * x = elem.inset->asInsetArgument())
1212 if (x->isTocCaption())
1216 // End custom AddToToc in paragraph layouts
1217 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1218 // execute the closing function
1219 closeAddToTocForParagraph(addtotoc_stack.top().first,
1220 addtotoc_stack.top().second, backend);
1221 addtotoc_stack.pop();
1224 // now the toc entry for the paragraph in the main table of contents
1225 int const toclevel = text().getTocLevel(pit);
1226 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1227 // insert this into the table of contents
1228 docstring tocstring;
1229 int const length = (doing_output && utype == OutputUpdate) ?
1230 INT_MAX : TOC_ENTRY_LENGTH;
1232 tocstring = par.labelString();
1233 if (!tocstring.empty())
1235 arginset->text().forOutliner(tocstring, length);
1237 par.forOutliner(tocstring, length);
1239 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1240 tocstring, doing_output));
1243 // And now the list of changes.
1244 par.addChangesToToc(dit, buffer(), doing_output, backend);
1249 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1250 DocIterator const & dit,
1252 TocBackend & backend) const
1254 Paragraph const & par = paragraphs()[pit];
1255 TocBuilder & b = backend.builder(par.layout().tocType());
1256 docstring const & label = par.labelString();
1257 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1258 return text().lastInSequence(pit);
1262 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1263 TocBackend & backend) const
1265 Paragraph const & par = paragraphs()[start];
1266 TocBuilder & b = backend.builder(par.layout().tocType());
1267 if (par.layout().isTocCaption()) {
1269 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1270 b.argumentItem(str);
1276 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1278 if (buffer().isClean())
1279 return Inset::notifyCursorLeaves(old, cur);
1281 // find text inset in old cursor
1282 Cursor insetCur = old;
1283 int scriptSlice = insetCur.find(this);
1284 // we can try to continue here. returning true means
1285 // the cursor is "now" invalid. which it was.
1286 LASSERT(scriptSlice != -1, return true);
1287 insetCur.cutOff(scriptSlice);
1288 LASSERT(&insetCur.inset() == this, return true);
1290 // update the old paragraph's words
1291 insetCur.paragraph().updateWords();
1293 return Inset::notifyCursorLeaves(old, cur);
1297 bool InsetText::completionSupported(Cursor const & cur) const
1299 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1300 return text_.completionSupported(cur);
1304 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1306 return completionSupported(cur);
1310 bool InsetText::automaticInlineCompletion() const
1312 return lyxrc.completion_inline_text;
1316 bool InsetText::automaticPopupCompletion() const
1318 return lyxrc.completion_popup_text;
1322 bool InsetText::showCompletionCursor() const
1324 return lyxrc.completion_cursor_text &&
1325 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1329 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1331 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1335 docstring InsetText::completionPrefix(Cursor const & cur) const
1337 if (!completionSupported(cur))
1339 return text_.completionPrefix(cur);
1343 bool InsetText::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1345 if (!completionSupported(cur))
1348 return text_.insertCompletion(cur, s);
1352 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1353 Dimension & dim) const
1355 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1356 tm.completionPosAndDim(cur, x, y, dim);
1360 string InsetText::contextMenu(BufferView const &, int, int) const
1362 string context_menu = contextMenuName();
1363 if (context_menu != InsetText::contextMenuName())
1364 context_menu += ";" + InsetText::contextMenuName();
1365 return context_menu;
1369 string InsetText::contextMenuName() const
1371 return "context-edit";
1375 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1377 OutputParams rp(&buffer().params().encoding());
1378 rp.for_tooltip = true;
1379 odocstringstream oss;
1382 ParagraphList::const_iterator beg = paragraphs().begin();
1383 ParagraphList::const_iterator end = paragraphs().end();
1384 ParagraphList::const_iterator it = beg;
1385 bool ref_printed = false;
1387 for (; it != end; ++it) {
1390 if ((*it).isRTL(buffer().params()))
1391 oss << "<div dir=\"rtl\">";
1392 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1393 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1396 docstring str = oss.str();
1398 str += from_ascii("\n\n") + _("[contains tracked changes]");
1399 support::truncateWithEllipsis(str, len);
1404 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1406 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1410 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1412 // Nested cprotect content needs \cprotect
1414 if (producesOutput() && hasCProtectContent(fragile))
1417 // Environments generally need cprotection in fragile context
1418 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1421 if (!getLayout().needsCProtect())
1424 // Environments and "no latex" types (e.g., knitr chunks)
1425 // need cprotection regardless the content
1426 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1429 // If the inset does not produce output (e.g. Note or Branch),
1430 // we can ignore the contained paragraphs
1431 if (!producesOutput())
1434 // Commands need cprotection if they contain specific chars
1435 int const nchars_escape = 9;
1436 static char_type const chars_escape[nchars_escape] = {
1437 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1439 ParagraphList const & pars = paragraphs();
1440 pit_type pend = pit_type(paragraphs().size());
1442 for (pit_type pit = 0; pit != pend; ++pit) {
1443 Paragraph const & par = pars[size_type(pit)];
1444 if (par.needsCProtection(fragile))
1446 docstring const par_str = par.asString();
1447 for (int k = 0; k < nchars_escape; k++) {
1448 if (!maintext && contains(par_str, chars_escape[k]))