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 // This should be OK because we are exporting
668 LASSERT(loader != nullptr, return);
669 loader->add(snippet);
670 loader->startLoading(true); // Generate the image and wait until done.
671 graphics::PreviewImage const * img = loader->preview(snippet);
672 LASSERT(img != nullptr, return);
673 support::FileName const & filename = img->filename();
675 // Use a file name that is only determined by the LaTeX code: the name of
676 // the snippet is more or less random (i.e., if the user generates the file
677 // several times, they will have a clutter of preview files).
678 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
679 // the file name will change a lot; two snippets are unlikely to have the
680 // same hash (by design of cryptographic hash functions). Computing a hash
681 // is typically slow, but extremely fast compared to compilation of the
682 // preview and image rendering.
683 std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(snippet)) + "." + filename.extension();
685 // Copy the image into the right folder.
686 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
688 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
689 // Start writing the DocBook code for the image.
690 xs << xml::StartTag("mediaobject")
693 // Output the rendered inset.
694 xs << xml::StartTag("imageobject")
696 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
698 << xml::EndTag("imageobject")
701 // Output the raw content.
702 xs << xml::StartTag("textobject")
704 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
705 docbookText(xs, rp, opts);
706 xs << xml::EndTag("programlisting")
708 << xml::EndTag("textobject")
711 xs << xml::EndTag("mediaobject");
715 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
717 InsetLayout const &il = getLayout();
718 OutputParams runparams = rp;
720 // In some cases, the input parameters must be overridden for outer tags.
721 bool writeOuterTag = opts & WriteOuterTag;
723 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
724 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
725 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
726 auto parSize = (size_t) par.size();
727 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
729 writeOuterTag = !allBibitems;
732 // Detect arguments that should be output before/after the paragraph.
733 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
734 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
735 std::set<InsetArgument const *> prependedArguments;
736 for (auto const & par : paragraphs()) {
737 for (pos_type i = 0; i < par.size(); ++i) {
738 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
739 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
740 if (arg->docbookargumentbeforemaintag())
741 prependedArguments.insert(par.getInset(i)->asInsetArgument());
746 std::set<InsetArgument const *> appendedArguments;
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->docbookargumentaftermaintag())
752 appendedArguments.insert(par.getInset(i)->asInsetArgument());
757 // Start outputting this inset.
758 // - First, wrapper around the inset and its main tag.
760 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
761 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
763 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
764 docstring attrs = docstring();
765 if (!il.docbookattr().empty())
766 attrs += from_ascii(il.docbookattr());
767 if (il.docbooktag() == "link")
768 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
769 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
772 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
773 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
776 // - Think about the arguments before the paragraph.
777 OutputParams np = runparams;
778 np.docbook_in_par = true;
779 for (auto const & arg : prependedArguments)
780 arg->docbook(xs, np);
782 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
783 runparams.docbook_prepended_arguments = std::move(prependedArguments);
784 runparams.docbook_appended_arguments = appendedArguments;
786 // - Deal with the first item.
787 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
789 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
790 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
792 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
793 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
796 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
798 // With respect to XHTML, paragraphs are still allowed here.
799 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
800 runparams.docbook_make_pars = false;
802 runparams.pass_thru = true;
804 // - Write the main content of the inset.
805 xs.startDivision(false);
806 docbookParagraphs(text_, buffer(), xs, runparams);
809 // - Think about the arguments after the paragraph.
810 for (auto const & arg : appendedArguments)
811 arg->docbook(xs, np);
813 // - Close the required tags.
815 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
816 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
818 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
819 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
821 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
822 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
824 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
825 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
827 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
828 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
833 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
835 return insetAsXHTML(xs, runparams, WriteEverything);
840 // There are cases where we may need to close open fonts and such
841 // and then re-open them when we are done. This would be the case, e.g.,
842 // if we were otherwise about to write:
843 // <em>word <div class='foot'>footnote text.</div> emph</em>
844 // The problem isn't so much that the footnote text will get emphasized:
845 // we can handle that with CSS. The problem is that this is invalid XHTML.
846 // One solution would be to make the footnote <span>, but the problem is
847 // completely general, and so we'd have to make absolutely everything into
848 // span. What I think will work is to check if we're about to write "div" and,
849 // if so, try to close fonts, etc.
850 // There are probably limits to how well we can do here, though, and we will
851 // have to rely upon users not putting footnotes inside noun-type insets.
852 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
853 XHTMLOptions opts) const
855 // we will always want to output all our paragraphs when we are
857 OutputParams runparams = rp;
858 runparams.par_begin = 0;
859 runparams.par_end = text().paragraphs().size();
862 xs.startDivision(false);
863 xhtmlParagraphs(text_, buffer(), xs, runparams);
868 InsetLayout const & il = getLayout();
869 if (opts & WriteOuterTag)
870 xs << xml::StartTag(il.htmltag(), il.htmlattr());
872 if ((opts & WriteLabel) && !il.counter().empty()) {
873 BufferParams const & bp = buffer().masterBuffer()->params();
874 Counters & cntrs = bp.documentClass().counters();
875 cntrs.step(il.counter(), OutputUpdate);
876 // FIXME: translate to paragraph language
877 if (!il.htmllabel().empty()) {
878 docstring const lbl =
879 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
880 // FIXME is this check necessary?
882 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
884 xs << xml::EndTag(il.htmllabeltag());
889 if (opts & WriteInnerTag)
890 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
892 // we will eventually lose information about the containing inset
893 if (!allowMultiPar() || opts == JustText)
894 runparams.html_make_pars = false;
896 runparams.pass_thru = true;
898 xs.startDivision(false);
899 xhtmlParagraphs(text_, buffer(), xs, runparams);
902 if (opts & WriteInnerTag)
903 xs << xml::EndTag(il.htmlinnertag());
905 if (opts & WriteOuterTag)
906 xs << xml::EndTag(il.htmltag());
912 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
913 bool const post) const
915 OutputParams runparams = runparams_in;
916 runparams.local_font =
917 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
919 runparams.pass_thru = true;
921 latexArgInsetsForParent(paragraphs(), os, runparams,
922 getLayout().postcommandargs(), "post:");
924 latexArgInsetsForParent(paragraphs(), os, runparams,
925 getLayout().latexargs());
929 void InsetText::cursorPos(BufferView const & bv,
930 CursorSlice const & sl, bool boundary, int & x, int & y) const
932 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
933 y = bv.textMetrics(&text_).cursorY(sl, boundary);
937 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
940 Paragraph & first = paragraphs().front();
941 for (unsigned int i = 0; i < data.length(); ++i)
942 first.insertChar(i, data[i], font, trackChanges);
946 void InsetText::setDrawFrame(bool flag)
952 ColorCode InsetText::frameColor() const
958 void InsetText::setFrameColor(ColorCode col)
964 void InsetText::appendParagraphs(ParagraphList & plist)
966 // There is little we can do here to keep track of changes.
967 // As of 2006/10/20, appendParagraphs is used exclusively by
968 // LyXTabular::setMultiColumn. In this context, the paragraph break
969 // is lost irreversibly and the appended text doesn't really change
971 ParagraphList & pl = paragraphs();
973 ParagraphList::iterator pit = plist.begin();
974 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
976 mergeParagraph(buffer().params(), pl,
977 distance(pl.begin(), ins) - 1);
979 ParagraphList::iterator const pend = plist.end();
980 for (; pit != pend; ++pit)
985 void InsetText::addPreview(DocIterator const & text_inset_pos,
986 graphics::PreviewLoader & loader) const
988 ParagraphList::const_iterator pit = paragraphs().begin();
989 ParagraphList::const_iterator pend = paragraphs().end();
992 DocIterator inset_pos = text_inset_pos;
993 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
995 for (; pit != pend; ++pit, ++pidx) {
996 InsetList::const_iterator it = pit->insetList().begin();
997 InsetList::const_iterator end = pit->insetList().end();
998 inset_pos.pit() = pidx;
999 for (; it != end; ++it) {
1000 inset_pos.pos() = it->pos;
1001 it->inset->addPreview(inset_pos, loader);
1007 ParagraphList const & InsetText::paragraphs() const
1009 return text_.paragraphs();
1013 ParagraphList & InsetText::paragraphs()
1015 return text_.paragraphs();
1019 bool InsetText::hasCProtectContent(bool fragile) const
1021 fragile |= getLayout().isNeedProtect();
1022 ParagraphList const & pars = paragraphs();
1023 pit_type pend = pit_type(paragraphs().size());
1024 for (pit_type pit = 0; pit != pend; ++pit) {
1025 Paragraph const & par = pars[size_type(pit)];
1026 if (par.needsCProtection(fragile))
1033 bool InsetText::insetAllowed(InsetCode code) const
1036 // Arguments, (plain) quotes and counter insets
1037 // are also allowed in PassThru insets
1043 return !isPassThru();
1048 bool InsetText::allowSpellCheck() const
1050 return getLayout().spellcheck() && !getLayout().isPassThru();
1054 bool InsetText::allowMultiPar() const
1056 return getLayout().isMultiPar();
1060 bool InsetText::forcePlainLayout(idx_type) const
1062 return getLayout().forcePlainLayout();
1066 bool InsetText::allowParagraphCustomization(idx_type) const
1068 return getLayout().allowParagraphCustomization();
1072 bool InsetText::forceLocalFontSwitch() const
1074 return getLayout().forceLocalFontSwitch();
1078 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1080 ParIterator it2 = it;
1082 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1083 if (producesOutput()) {
1084 InsetLayout const & il = getLayout();
1085 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1086 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1088 // LYXERR0("Entering " << name());
1089 cnt.clearLastLayout();
1090 // FIXME cnt.saveLastCounter()?
1092 buffer().updateBuffer(it2, utype, deleted);
1094 // LYXERR0("Exiting " << name());
1095 cnt.restoreLastLayout();
1096 // FIXME cnt.restoreLastCounter()?
1098 // Record if this inset is embedded in a title layout
1099 // This is needed to decide when \maketitle is output.
1100 intitle_context_ = it.paragraph().layout().intitle;
1101 // Also check embedding layouts
1102 size_t const n = it.depth();
1103 for (size_t i = 0; i < n; ++i) {
1104 if (it[i].paragraph().layout().intitle) {
1105 intitle_context_ = true;
1110 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1111 // Note that we do not need to call:
1112 // tclass.counters().clearLastLayout()
1113 // since we are saving and restoring the existing counters, etc.
1114 Counters savecnt = tclass.counters();
1115 tclass.counters().reset();
1116 // we need float information even in note insets (#9760)
1117 tclass.counters().current_float(savecnt.current_float());
1118 tclass.counters().isSubfloat(savecnt.isSubfloat());
1119 buffer().updateBuffer(it2, utype, deleted);
1120 tclass.counters() = move(savecnt);
1125 void InsetText::toString(odocstream & os) const
1127 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1131 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1132 bool const shorten) const
1134 if (!getLayout().isInToc())
1136 text().forOutliner(os, maxlen, shorten);
1140 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1141 UpdateType utype, TocBackend & backend) const
1143 DocIterator dit = cdit;
1144 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1145 iterateForToc(dit, output_active, utype, backend);
1149 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1150 UpdateType utype, TocBackend & backend) const
1152 DocIterator dit = cdit;
1153 // This also ensures that any document has a table of contents
1154 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1156 BufferParams const & bufparams = buffer_->params();
1157 int const min_toclevel = bufparams.documentClass().min_toclevel();
1158 // we really should have done this before we got here, but it
1159 // can't hurt too much to do it again
1160 bool const doing_output = output_active && producesOutput();
1162 // For each paragraph,
1163 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1164 // paragraphs as needed.
1165 // * Traverse its insets and let them add their toc items
1166 // * Compute the main table of contents (this is hardcoded)
1167 // * Add the list of changes
1168 ParagraphList const & pars = paragraphs();
1169 pit_type pend = paragraphs().size();
1170 // Record pairs {start,end} of where a toc item was opened for a paragraph
1171 // and where it must be closed
1172 stack<pair<pit_type, pit_type>> addtotoc_stack;
1174 for (pit_type pit = 0; pit != pend; ++pit) {
1175 Paragraph const & par = pars[pit];
1179 // Custom AddToToc in paragraph layouts (i.e. theorems)
1180 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1182 openAddToTocForParagraph(pit, dit, output_active, backend);
1183 addtotoc_stack.push({pit, end});
1186 // If we find an InsetArgument that is supposed to provide the TOC caption,
1187 // we'll save it for use later.
1188 InsetArgument const * arginset = nullptr;
1189 for (auto const & table : par.insetList()) {
1190 dit.pos() = table.pos;
1191 table.inset->addToToc(dit, doing_output, utype, backend);
1192 if (InsetArgument const * x = table.inset->asInsetArgument())
1193 if (x->isTocCaption())
1197 // End custom AddToToc in paragraph layouts
1198 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1199 // execute the closing function
1200 closeAddToTocForParagraph(addtotoc_stack.top().first,
1201 addtotoc_stack.top().second, backend);
1202 addtotoc_stack.pop();
1205 // now the toc entry for the paragraph in the main table of contents
1206 int const toclevel = text().getTocLevel(pit);
1207 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1208 // insert this into the table of contents
1209 docstring tocstring;
1210 int const length = (doing_output && utype == OutputUpdate) ?
1211 INT_MAX : TOC_ENTRY_LENGTH;
1213 tocstring = par.labelString();
1214 if (!tocstring.empty())
1216 arginset->text().forOutliner(tocstring, length);
1218 par.forOutliner(tocstring, length);
1220 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1221 tocstring, doing_output));
1224 // And now the list of changes.
1225 par.addChangesToToc(dit, buffer(), doing_output, backend);
1230 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1231 DocIterator const & dit,
1233 TocBackend & backend) const
1235 Paragraph const & par = paragraphs()[pit];
1236 TocBuilder & b = backend.builder(par.layout().tocType());
1237 docstring const & label = par.labelString();
1238 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1239 return text().lastInSequence(pit);
1243 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1244 TocBackend & backend) const
1246 Paragraph const & par = paragraphs()[start];
1247 TocBuilder & b = backend.builder(par.layout().tocType());
1248 if (par.layout().isTocCaption()) {
1250 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1251 b.argumentItem(str);
1257 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1259 if (buffer().isClean())
1260 return Inset::notifyCursorLeaves(old, cur);
1262 // find text inset in old cursor
1263 Cursor insetCur = old;
1264 int scriptSlice = insetCur.find(this);
1265 // we can try to continue here. returning true means
1266 // the cursor is "now" invalid. which it was.
1267 LASSERT(scriptSlice != -1, return true);
1268 insetCur.cutOff(scriptSlice);
1269 LASSERT(&insetCur.inset() == this, return true);
1271 // update the old paragraph's words
1272 insetCur.paragraph().updateWords();
1274 return Inset::notifyCursorLeaves(old, cur);
1278 bool InsetText::completionSupported(Cursor const & cur) const
1280 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1281 return text_.completionSupported(cur);
1285 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1287 return completionSupported(cur);
1291 bool InsetText::automaticInlineCompletion() const
1293 return lyxrc.completion_inline_text;
1297 bool InsetText::automaticPopupCompletion() const
1299 return lyxrc.completion_popup_text;
1303 bool InsetText::showCompletionCursor() const
1305 return lyxrc.completion_cursor_text &&
1306 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1310 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1312 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1316 docstring InsetText::completionPrefix(Cursor const & cur) const
1318 if (!completionSupported(cur))
1320 return text_.completionPrefix(cur);
1324 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1327 if (!completionSupported(cur))
1330 return text_.insertCompletion(cur, s, finished);
1334 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1335 Dimension & dim) const
1337 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1338 tm.completionPosAndDim(cur, x, y, dim);
1342 string InsetText::contextMenu(BufferView const &, int, int) const
1344 string context_menu = contextMenuName();
1345 if (context_menu != InsetText::contextMenuName())
1346 context_menu += ";" + InsetText::contextMenuName();
1347 return context_menu;
1351 string InsetText::contextMenuName() const
1353 return "context-edit";
1357 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1359 OutputParams rp(&buffer().params().encoding());
1360 rp.for_tooltip = true;
1361 odocstringstream oss;
1364 ParagraphList::const_iterator beg = paragraphs().begin();
1365 ParagraphList::const_iterator end = paragraphs().end();
1366 ParagraphList::const_iterator it = beg;
1367 bool ref_printed = false;
1369 for (; it != end; ++it) {
1372 if ((*it).isRTL(buffer().params()))
1373 oss << "<div dir=\"rtl\">";
1374 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1375 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1378 docstring str = oss.str();
1380 str += from_ascii("\n\n") + _("[contains tracked changes]");
1381 support::truncateWithEllipsis(str, len);
1386 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1388 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1392 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1394 // Nested cprotect content needs \cprotect
1396 if (producesOutput() && hasCProtectContent(fragile))
1399 // Environments generally need cprotection in fragile context
1400 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1403 if (!getLayout().needsCProtect())
1406 // Environments and "no latex" types (e.g., knitr chunks)
1407 // need cprotection regardless the content
1408 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1411 // If the inset does not produce output (e.g. Note or Branch),
1412 // we can ignore the contained paragraphs
1413 if (!producesOutput())
1416 // Commands need cprotection if they contain specific chars
1417 int const nchars_escape = 9;
1418 static char_type const chars_escape[nchars_escape] = {
1419 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1421 ParagraphList const & pars = paragraphs();
1422 pit_type pend = pit_type(paragraphs().size());
1424 for (pit_type pit = 0; pit != pend; ++pit) {
1425 Paragraph const & par = pars[size_type(pit)];
1426 if (par.needsCProtection(fragile))
1428 docstring const par_str = par.asString();
1429 for (int k = 0; k < nchars_escape; k++) {
1430 if (contains(par_str, chars_escape[k]))