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();
489 if (il.forceOwnlines())
491 bool needendgroup = false;
492 if (!il.latexname().empty()) {
493 if (il.latextype() == InsetLaTeXType::COMMAND) {
495 // FIXME \protect should only be used for fragile
496 // commands, but we do not provide this information yet.
497 if (hasCProtectContent(runparams.moving_arg)) {
498 if (contains(runparams.active_chars, '^')) {
499 // cprotect relies on ^ being on catcode 7
500 os << "\\begingroup\\catcode`\\^=7";
504 } else if (runparams.moving_arg)
506 os << '\\' << from_utf8(il.latexname());
507 if (!il.latexargs().empty())
508 getArgs(os, runparams);
509 if (!il.latexparam().empty())
510 os << from_utf8(il.latexparam());
512 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
517 if (runparams.lastid != -1)
518 os.texrow().start(runparams.lastid,
520 os << "\\begin{" << from_utf8(il.latexname()) << "}";
521 if (!il.latexargs().empty())
522 getArgs(os, runparams);
523 if (!il.latexparam().empty())
524 os << from_utf8(il.latexparam());
528 if (!il.latexargs().empty())
529 getArgs(os, runparams);
530 if (!il.latexparam().empty())
531 os << from_utf8(il.latexparam());
534 if (!il.leftdelim().empty())
535 os << il.leftdelim();
537 OutputParams rp = runparams;
540 if (il.isNeedProtect())
541 rp.moving_arg = true;
542 if (il.isNeedMBoxProtect())
544 if (!il.passThruChars().empty())
545 rp.pass_thru_chars += il.passThruChars();
546 if (!il.newlineCmd().empty())
547 rp.newlinecmd = il.newlineCmd();
549 rp.par_end = paragraphs().size();
551 // Output the contents of the inset
552 latexParagraphs(buffer(), text_, os, rp);
553 runparams.encoding = rp.encoding;
554 // Pass the post_macros upstream
555 runparams.post_macro = rp.post_macro;
556 // These need to be passed upstream as well
557 runparams.need_maketitle = rp.need_maketitle;
558 runparams.have_maketitle = rp.have_maketitle;
560 if (!il.rightdelim().empty())
561 os << il.rightdelim();
563 if (!il.latexname().empty()) {
564 if (il.latextype() == InsetLaTeXType::COMMAND) {
566 if (!il.postcommandargs().empty())
567 getArgs(os, runparams, true);
570 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
571 // A comment environment doesn't need a % before \n\end
572 if (il.isDisplay() || runparams.inComment)
576 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
578 os.protectSpace(true);
581 if (il.forceOwnlines())
586 int InsetText::plaintext(odocstringstream & os,
587 OutputParams const & runparams, size_t max_length) const
589 ParagraphList::const_iterator beg = paragraphs().begin();
590 ParagraphList::const_iterator end = paragraphs().end();
591 ParagraphList::const_iterator it = beg;
592 bool ref_printed = false;
594 for (; it != end; ++it) {
597 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
600 odocstringstream oss;
601 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
602 docstring const str = oss.str();
604 // FIXME: len is not computed fully correctly; in principle,
605 // we have to count the characters after the last '\n'
607 if (os.str().size() >= max_length)
615 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
617 docbook(xs, rp, WriteEverything);
621 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
623 // Always output all the paragraphs.
624 OutputParams runparams = rp;
625 runparams.par_begin = 0;
626 runparams.par_end = text().paragraphs().size();
629 xs.startDivision(false);
630 docbookParagraphs(text_, buffer(), xs, runparams);
635 InsetLayout const &il = getLayout();
637 // Maybe this is an <info> paragraph that should not be generated
638 // at all (i.e. right now, its place is somewhere else, typically outside
639 // the current paragraph).
640 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
643 // Maybe this inset must be rendered before being output.
644 if (il.docbookrenderasimage()) {
645 docbookRenderAsImage(xs, runparams, opts);
649 // If none of the special cases before apply, output the inset.
650 docbookText(xs, runparams, opts);
654 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
656 LASSERT(getLayout().docbookrenderasimage(), return);
658 // Generate the LaTeX code to compile in order to get the image.
659 // This code actually does the same as an InsetPreview, but without
661 // Also, the image must be generated before the DocBook output is finished,
662 // unlike a preview that is not immediately required for display.
663 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
664 std::string const snippet = support::trim(to_utf8(latex_snippet));
665 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
667 graphics::PreviewLoader* loader = buffer().loader();
668 // This should be OK because we are exporting
669 LASSERT(loader != nullptr, return);
670 loader->add(snippet);
671 loader->startLoading(true); // Generate the image and wait until done.
672 graphics::PreviewImage const * img = loader->preview(snippet);
673 LASSERT(img != nullptr, return);
674 support::FileName const & filename = img->filename();
676 // Use a file name that is only determined by the LaTeX code: the name of
677 // the snippet is more or less random (i.e., if the user generates the file
678 // several times, they will have a clutter of preview files).
679 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
680 // the file name will change a lot; two snippets are unlikely to have the
681 // same hash (by design of cryptographic hash functions). Computing a hash
682 // is typically slow, but extremely fast compared to compilation of the
683 // preview and image rendering.
684 std::string newFileName = "lyx_" + sanitizeFileName(toHexHash(snippet)) + "." + filename.extension();
686 // Copy the image into the right folder.
687 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
689 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
690 // Start writing the DocBook code for the image.
691 xs << xml::StartTag("mediaobject")
694 // Output the rendered inset.
695 xs << xml::StartTag("imageobject")
697 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
699 << xml::EndTag("imageobject")
702 // Output the raw content.
703 xs << xml::StartTag("textobject")
705 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
706 docbookText(xs, rp, opts);
707 xs << xml::EndTag("programlisting")
709 << xml::EndTag("textobject")
712 xs << xml::EndTag("mediaobject");
716 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
718 InsetLayout const &il = getLayout();
719 OutputParams runparams = rp;
721 // In some cases, the input parameters must be overridden for outer tags.
722 bool writeOuterTag = opts & WriteOuterTag;
724 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
725 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
726 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
727 auto parSize = (size_t) par.size();
728 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
730 writeOuterTag = !allBibitems;
733 // Detect arguments that should be output before/after the paragraph.
734 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
735 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
736 std::set<InsetArgument const *> prependedArguments;
737 for (auto const & par : paragraphs()) {
738 for (pos_type i = 0; i < par.size(); ++i) {
739 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
740 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
741 if (arg->docbookargumentbeforemaintag())
742 prependedArguments.insert(par.getInset(i)->asInsetArgument());
747 std::set<InsetArgument const *> appendedArguments;
748 for (auto const & par : paragraphs()) {
749 for (pos_type i = 0; i < par.size(); ++i) {
750 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
751 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
752 if (arg->docbookargumentaftermaintag())
753 appendedArguments.insert(par.getInset(i)->asInsetArgument());
758 // Start outputting this inset.
759 // - First, wrapper around the inset and its main tag.
761 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
762 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
764 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
765 docstring attrs = docstring();
766 if (!il.docbookattr().empty())
767 attrs += from_ascii(il.docbookattr());
768 if (il.docbooktag() == "link")
769 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
770 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
773 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
774 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
777 // - Think about the arguments before the paragraph.
778 OutputParams np = runparams;
779 np.docbook_in_par = true;
780 for (auto const & arg : prependedArguments)
781 arg->docbook(xs, np);
783 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
784 runparams.docbook_prepended_arguments = std::move(prependedArguments);
785 runparams.docbook_appended_arguments = appendedArguments;
787 // - Deal with the first item.
788 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
790 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
791 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
793 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
794 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
797 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
799 // With respect to XHTML, paragraphs are still allowed here.
800 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
801 runparams.docbook_make_pars = false;
803 runparams.pass_thru = true;
805 // - Write the main content of the inset.
806 xs.startDivision(false);
807 docbookParagraphs(text_, buffer(), xs, runparams);
810 // - Think about the arguments after the paragraph.
811 for (auto const & arg : appendedArguments)
812 arg->docbook(xs, np);
814 // - Close the required tags.
816 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
817 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
819 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
820 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
822 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
823 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
825 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
826 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
828 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
829 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
834 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
836 return insetAsXHTML(xs, runparams, WriteEverything);
841 // There are cases where we may need to close open fonts and such
842 // and then re-open them when we are done. This would be the case, e.g.,
843 // if we were otherwise about to write:
844 // <em>word <div class='foot'>footnote text.</div> emph</em>
845 // The problem isn't so much that the footnote text will get emphasized:
846 // we can handle that with CSS. The problem is that this is invalid XHTML.
847 // One solution would be to make the footnote <span>, but the problem is
848 // completely general, and so we'd have to make absolutely everything into
849 // span. What I think will work is to check if we're about to write "div" and,
850 // if so, try to close fonts, etc.
851 // There are probably limits to how well we can do here, though, and we will
852 // have to rely upon users not putting footnotes inside noun-type insets.
853 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
854 XHTMLOptions opts) const
856 // we will always want to output all our paragraphs when we are
858 OutputParams runparams = rp;
859 runparams.par_begin = 0;
860 runparams.par_end = text().paragraphs().size();
863 xs.startDivision(false);
864 xhtmlParagraphs(text_, buffer(), xs, runparams);
869 InsetLayout const & il = getLayout();
870 if (opts & WriteOuterTag)
871 xs << xml::StartTag(il.htmltag(), il.htmlattr());
873 if ((opts & WriteLabel) && !il.counter().empty()) {
874 BufferParams const & bp = buffer().masterBuffer()->params();
875 Counters & cntrs = bp.documentClass().counters();
876 cntrs.step(il.counter(), OutputUpdate);
877 // FIXME: translate to paragraph language
878 if (!il.htmllabel().empty()) {
879 docstring const lbl =
880 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
881 // FIXME is this check necessary?
883 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
885 xs << xml::EndTag(il.htmllabeltag());
890 if (opts & WriteInnerTag)
891 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
893 // we will eventually lose information about the containing inset
894 if (!allowMultiPar() || opts == JustText)
895 runparams.html_make_pars = false;
897 runparams.pass_thru = true;
899 xs.startDivision(false);
900 xhtmlParagraphs(text_, buffer(), xs, runparams);
903 if (opts & WriteInnerTag)
904 xs << xml::EndTag(il.htmlinnertag());
906 if (opts & WriteOuterTag)
907 xs << xml::EndTag(il.htmltag());
913 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
914 bool const post) const
916 OutputParams runparams = runparams_in;
917 runparams.local_font =
918 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
920 runparams.pass_thru = true;
922 latexArgInsetsForParent(paragraphs(), os, runparams,
923 getLayout().postcommandargs(), "post:");
925 latexArgInsetsForParent(paragraphs(), os, runparams,
926 getLayout().latexargs());
930 void InsetText::cursorPos(BufferView const & bv,
931 CursorSlice const & sl, bool boundary, int & x, int & y) const
933 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
934 y = bv.textMetrics(&text_).cursorY(sl, boundary);
938 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
941 Paragraph & first = paragraphs().front();
942 for (unsigned int i = 0; i < data.length(); ++i)
943 first.insertChar(i, data[i], font, trackChanges);
947 void InsetText::setDrawFrame(bool flag)
953 ColorCode InsetText::frameColor() const
959 void InsetText::setFrameColor(ColorCode col)
965 void InsetText::appendParagraphs(ParagraphList & plist)
967 // There is little we can do here to keep track of changes.
968 // As of 2006/10/20, appendParagraphs is used exclusively by
969 // LyXTabular::setMultiColumn. In this context, the paragraph break
970 // is lost irreversibly and the appended text doesn't really change
972 ParagraphList & pl = paragraphs();
974 ParagraphList::iterator pit = plist.begin();
975 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
977 mergeParagraph(buffer().params(), pl,
978 distance(pl.begin(), ins) - 1);
980 ParagraphList::iterator const pend = plist.end();
981 for (; pit != pend; ++pit)
986 void InsetText::addPreview(DocIterator const & text_inset_pos,
987 graphics::PreviewLoader & loader) const
989 ParagraphList::const_iterator pit = paragraphs().begin();
990 ParagraphList::const_iterator pend = paragraphs().end();
993 DocIterator inset_pos = text_inset_pos;
994 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
996 for (; pit != pend; ++pit, ++pidx) {
997 InsetList::const_iterator it = pit->insetList().begin();
998 InsetList::const_iterator end = pit->insetList().end();
999 inset_pos.pit() = pidx;
1000 for (; it != end; ++it) {
1001 inset_pos.pos() = it->pos;
1002 it->inset->addPreview(inset_pos, loader);
1008 ParagraphList const & InsetText::paragraphs() const
1010 return text_.paragraphs();
1014 ParagraphList & InsetText::paragraphs()
1016 return text_.paragraphs();
1020 bool InsetText::hasCProtectContent(bool fragile) const
1022 fragile |= getLayout().isNeedProtect();
1023 ParagraphList const & pars = paragraphs();
1024 pit_type pend = pit_type(paragraphs().size());
1025 for (pit_type pit = 0; pit != pend; ++pit) {
1026 Paragraph const & par = pars[size_type(pit)];
1027 if (par.needsCProtection(fragile))
1034 bool InsetText::insetAllowed(InsetCode code) const
1037 // Arguments, (plain) quotes and counter insets
1038 // are also allowed in PassThru insets
1043 // These are only allowed in index insets
1044 case INDEXMACRO_CODE:
1045 case INDEXMACRO_SORTKEY_CODE:
1048 return !isPassThru();
1053 bool InsetText::allowSpellCheck() const
1055 return getLayout().spellcheck() && !getLayout().isPassThru();
1059 bool InsetText::allowMultiPar() const
1061 return getLayout().isMultiPar();
1065 bool InsetText::forcePlainLayout(idx_type) const
1067 return getLayout().forcePlainLayout();
1071 bool InsetText::allowParagraphCustomization(idx_type) const
1073 return getLayout().allowParagraphCustomization();
1077 bool InsetText::forceLocalFontSwitch() const
1079 return getLayout().forceLocalFontSwitch();
1083 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1085 ParIterator it2 = it;
1087 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1088 if (producesOutput()) {
1089 InsetLayout const & il = getLayout();
1090 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1091 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1093 // LYXERR0("Entering " << name());
1094 cnt.clearLastLayout();
1095 // FIXME cnt.saveLastCounter()?
1097 buffer().updateBuffer(it2, utype, deleted);
1099 // LYXERR0("Exiting " << name());
1100 cnt.restoreLastLayout();
1101 // FIXME cnt.restoreLastCounter()?
1103 // Record if this inset is embedded in a title layout
1104 // This is needed to decide when \maketitle is output.
1105 intitle_context_ = it.paragraph().layout().intitle;
1106 // Also check embedding layouts
1107 size_t const n = it.depth();
1108 for (size_t i = 0; i < n; ++i) {
1109 if (it[i].paragraph().layout().intitle) {
1110 intitle_context_ = true;
1115 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1116 // Note that we do not need to call:
1117 // tclass.counters().clearLastLayout()
1118 // since we are saving and restoring the existing counters, etc.
1119 Counters savecnt = tclass.counters();
1120 tclass.counters().reset();
1121 // we need float information even in note insets (#9760)
1122 tclass.counters().current_float(savecnt.current_float());
1123 tclass.counters().isSubfloat(savecnt.isSubfloat());
1124 buffer().updateBuffer(it2, utype, deleted);
1125 tclass.counters() = std::move(savecnt);
1130 void InsetText::toString(odocstream & os) const
1132 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1136 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1137 bool const shorten) const
1139 if (!getLayout().isInToc())
1141 text().forOutliner(os, maxlen, shorten);
1145 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1146 UpdateType utype, TocBackend & backend) const
1148 DocIterator dit = cdit;
1149 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1150 iterateForToc(dit, output_active, utype, backend);
1154 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1155 UpdateType utype, TocBackend & backend) const
1157 DocIterator dit = cdit;
1158 // This also ensures that any document has a table of contents
1159 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1161 BufferParams const & bufparams = buffer_->params();
1162 int const min_toclevel = bufparams.documentClass().min_toclevel();
1163 // we really should have done this before we got here, but it
1164 // can't hurt too much to do it again
1165 bool const doing_output = output_active && producesOutput();
1167 // For each paragraph,
1168 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1169 // paragraphs as needed.
1170 // * Traverse its insets and let them add their toc items
1171 // * Compute the main table of contents (this is hardcoded)
1172 // * Add the list of changes
1173 ParagraphList const & pars = paragraphs();
1174 pit_type pend = paragraphs().size();
1175 // Record pairs {start,end} of where a toc item was opened for a paragraph
1176 // and where it must be closed
1177 stack<pair<pit_type, pit_type>> addtotoc_stack;
1179 for (pit_type pit = 0; pit != pend; ++pit) {
1180 Paragraph const & par = pars[pit];
1184 // Custom AddToToc in paragraph layouts (i.e. theorems)
1185 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1187 openAddToTocForParagraph(pit, dit, output_active, backend);
1188 addtotoc_stack.push({pit, end});
1191 // If we find an InsetArgument that is supposed to provide the TOC caption,
1192 // we'll save it for use later.
1193 InsetArgument const * arginset = nullptr;
1194 for (auto const & table : par.insetList()) {
1195 dit.pos() = table.pos;
1196 table.inset->addToToc(dit, doing_output, utype, backend);
1197 if (InsetArgument const * x = table.inset->asInsetArgument())
1198 if (x->isTocCaption())
1202 // End custom AddToToc in paragraph layouts
1203 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1204 // execute the closing function
1205 closeAddToTocForParagraph(addtotoc_stack.top().first,
1206 addtotoc_stack.top().second, backend);
1207 addtotoc_stack.pop();
1210 // now the toc entry for the paragraph in the main table of contents
1211 int const toclevel = text().getTocLevel(pit);
1212 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1213 // insert this into the table of contents
1214 docstring tocstring;
1215 int const length = (doing_output && utype == OutputUpdate) ?
1216 INT_MAX : TOC_ENTRY_LENGTH;
1218 tocstring = par.labelString();
1219 if (!tocstring.empty())
1221 arginset->text().forOutliner(tocstring, length);
1223 par.forOutliner(tocstring, length);
1225 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1226 tocstring, doing_output));
1229 // And now the list of changes.
1230 par.addChangesToToc(dit, buffer(), doing_output, backend);
1235 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1236 DocIterator const & dit,
1238 TocBackend & backend) const
1240 Paragraph const & par = paragraphs()[pit];
1241 TocBuilder & b = backend.builder(par.layout().tocType());
1242 docstring const & label = par.labelString();
1243 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1244 return text().lastInSequence(pit);
1248 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1249 TocBackend & backend) const
1251 Paragraph const & par = paragraphs()[start];
1252 TocBuilder & b = backend.builder(par.layout().tocType());
1253 if (par.layout().isTocCaption()) {
1255 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1256 b.argumentItem(str);
1262 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1264 if (buffer().isClean())
1265 return Inset::notifyCursorLeaves(old, cur);
1267 // find text inset in old cursor
1268 Cursor insetCur = old;
1269 int scriptSlice = insetCur.find(this);
1270 // we can try to continue here. returning true means
1271 // the cursor is "now" invalid. which it was.
1272 LASSERT(scriptSlice != -1, return true);
1273 insetCur.cutOff(scriptSlice);
1274 LASSERT(&insetCur.inset() == this, return true);
1276 // update the old paragraph's words
1277 insetCur.paragraph().updateWords();
1279 return Inset::notifyCursorLeaves(old, cur);
1283 bool InsetText::completionSupported(Cursor const & cur) const
1285 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1286 return text_.completionSupported(cur);
1290 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1292 return completionSupported(cur);
1296 bool InsetText::automaticInlineCompletion() const
1298 return lyxrc.completion_inline_text;
1302 bool InsetText::automaticPopupCompletion() const
1304 return lyxrc.completion_popup_text;
1308 bool InsetText::showCompletionCursor() const
1310 return lyxrc.completion_cursor_text &&
1311 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1315 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1317 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1321 docstring InsetText::completionPrefix(Cursor const & cur) const
1323 if (!completionSupported(cur))
1325 return text_.completionPrefix(cur);
1329 bool InsetText::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1331 if (!completionSupported(cur))
1334 return text_.insertCompletion(cur, s);
1338 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1339 Dimension & dim) const
1341 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1342 tm.completionPosAndDim(cur, x, y, dim);
1346 string InsetText::contextMenu(BufferView const &, int, int) const
1348 string context_menu = contextMenuName();
1349 if (context_menu != InsetText::contextMenuName())
1350 context_menu += ";" + InsetText::contextMenuName();
1351 return context_menu;
1355 string InsetText::contextMenuName() const
1357 return "context-edit";
1361 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1363 OutputParams rp(&buffer().params().encoding());
1364 rp.for_tooltip = true;
1365 odocstringstream oss;
1368 ParagraphList::const_iterator beg = paragraphs().begin();
1369 ParagraphList::const_iterator end = paragraphs().end();
1370 ParagraphList::const_iterator it = beg;
1371 bool ref_printed = false;
1373 for (; it != end; ++it) {
1376 if ((*it).isRTL(buffer().params()))
1377 oss << "<div dir=\"rtl\">";
1378 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1379 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1382 docstring str = oss.str();
1384 str += from_ascii("\n\n") + _("[contains tracked changes]");
1385 support::truncateWithEllipsis(str, len);
1390 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1392 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1396 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1398 // Nested cprotect content needs \cprotect
1400 if (producesOutput() && hasCProtectContent(fragile))
1403 // Environments generally need cprotection in fragile context
1404 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1407 if (!getLayout().needsCProtect())
1410 // Environments and "no latex" types (e.g., knitr chunks)
1411 // need cprotection regardless the content
1412 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1415 // If the inset does not produce output (e.g. Note or Branch),
1416 // we can ignore the contained paragraphs
1417 if (!producesOutput())
1420 // Commands need cprotection if they contain specific chars
1421 int const nchars_escape = 9;
1422 static char_type const chars_escape[nchars_escape] = {
1423 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1425 ParagraphList const & pars = paragraphs();
1426 pit_type pend = pit_type(paragraphs().size());
1428 for (pit_type pit = 0; pit != pend; ++pit) {
1429 Paragraph const & par = pars[size_type(pit)];
1430 if (par.needsCProtection(fragile))
1432 docstring const par_str = par.asString();
1433 for (int k = 0; k < nchars_escape; k++) {
1434 if (contains(par_str, chars_escape[k]))