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/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/Changer.h"
70 #include "support/FileName.h"
77 using namespace lyx::support;
82 /////////////////////////////////////////////////////////////////////
84 InsetText::InsetText(Buffer * buf, UsePlain type)
85 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
86 frame_color_(Color_insetframe),
87 text_(this, type == DefaultLayout)
92 InsetText::InsetText(InsetText const & in)
93 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
94 intitle_context_(false), frame_color_(in.frame_color_),
100 void InsetText::setBuffer(Buffer & buf)
102 ParagraphList::iterator end = paragraphs().end();
103 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
104 it->setInsetBuffers(buf);
105 Inset::setBuffer(buf);
109 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
111 text_.setMacrocontextPosition(pos);
113 ParagraphList::const_iterator pit = paragraphs().begin();
114 ParagraphList::const_iterator pend = paragraphs().end();
115 for (; pit != pend; ++pit) {
116 InsetList::const_iterator iit = pit->insetList().begin();
117 InsetList::const_iterator end = pit->insetList().end();
118 for (; iit != end; ++iit) {
119 if (InsetText * txt = iit->inset->asInsetText()) {
120 DocIterator ppos(pos);
121 ppos.push_back(CursorSlice(*txt));
122 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
129 void InsetText::clear()
131 ParagraphList & pars = paragraphs();
132 LBUFERR(!pars.empty());
134 // This is a gross hack...
135 Layout const & old_layout = pars.begin()->layout();
138 pars.push_back(Paragraph());
139 pars.begin()->setInsetOwner(this);
140 pars.begin()->setLayout(old_layout);
144 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
146 TextMetrics const & tm = bv.textMetrics(&text_);
147 Dimension dim = tm.dim();
148 dim.wid += leftOffset(&bv) + rightOffset(&bv);
149 dim.des += bottomOffset(&bv);
150 dim.asc += topOffset(&bv);
155 void InsetText::write(ostream & os) const
162 void InsetText::read(Lexer & lex)
166 // delete the initial paragraph
167 Paragraph oldpar = *paragraphs().begin();
168 paragraphs().clear();
170 lex.setContext("InsetText::read");
171 bool res = text_.read(lex, errorList, this);
174 lex.printError("Missing \\end_inset at this point. ");
177 // ensure we have at least one paragraph.
178 if (paragraphs().empty())
179 paragraphs().push_back(oldpar);
180 // Force default font, if so requested
181 // This avoids paragraphs in buffer language that would have a
182 // foreign language after a document language change, and it ensures
183 // that all new text in ERT and similar gets the "latex" language,
184 // since new text inherits the language from the last position of the
185 // existing text. As a side effect this makes us also robust against
186 // bugs in LyX that might lead to font changes in ERT in .lyx files.
191 void InsetText::setOuterFont(BufferView & bv, FontInfo const & outer) const
193 TextMetrics & tm = bv.textMetrics(&text_);
194 FontInfo tmpfont = getFont();
195 tmpfont.realize(outer);
196 tm.font_.fontInfo() = tmpfont;
200 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
202 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
204 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
206 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
207 mi.base.textwidth -= horiz_offset;
209 // Remember the full outer font
210 setOuterFont(*mi.base.bv, mi.base.font);
211 // and use it in these metrics computation.
212 mi.base.font = tm.font_.fontInfo();
214 // This can happen when a layout has a left and right margin,
215 // and the view is made very narrow. We can't do better than
216 // to draw it partly out of view (bug 5890).
217 if (mi.base.textwidth < 1)
218 mi.base.textwidth = 1;
221 tm.metrics(mi, dim, mi.base.textwidth);
224 mi.base.textwidth += horiz_offset;
225 dim.asc += topOffset(mi.base.bv);
226 dim.des += bottomOffset(mi.base.bv);
227 dim.wid += horiz_offset;
231 void InsetText::draw(PainterInfo & pi, int x, int y) const
233 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
235 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
236 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
237 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
238 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
239 int const xframe = x + leftOffset(pi.base.bv) / 2;
240 bool change_drawn = false;
242 pi.pain.fillRectangle(xframe, yframe, w, h,
243 pi.backgroundColor(this));
246 Changer dummy = changeVar(pi.background_color,
247 pi.backgroundColor(this, false));
248 // The change tracking cue must not be inherited
249 Changer dummy2 = changeVar(pi.change, Change());
250 tm.draw(pi, x + leftOffset(pi.base.bv), y);
254 // Change color of the frame in tracked changes, like for tabulars.
255 // Only do so if the color is not custom. But do so even if RowPainter
256 // handles the strike-through already.
258 if (pi.change.changed()
259 // Originally, these are the colors with role Text, from role() in
260 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
261 // types, and also maybe it need not match in the future.
262 && (frameColor() == Color_foreground
263 || frameColor() == Color_cursor
264 || frameColor() == Color_preview
265 || frameColor() == Color_tabularline
266 || frameColor() == Color_previewframe)) {
267 c = pi.change.color();
271 pi.pain.rectangle(xframe, yframe, w, h, c);
274 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
275 // Do not draw the change tracking cue if already done by RowPainter and
276 // do not draw the cue for INSERTED if the information is already in the
277 // color of the frame
278 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
282 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
284 pit_type const pit = front ? 0 : paragraphs().size() - 1;
285 pos_type pos = front ? 0 : paragraphs().back().size();
287 // if visual information is not to be ignored, move to extreme right/left
288 if (entry_from != ENTRY_DIRECTION_IGNORE) {
289 Cursor temp_cur = cur;
290 temp_cur.pit() = pit;
291 temp_cur.pos() = pos;
292 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
293 pos = temp_cur.pos();
296 cur.top().setPitPos(pit, pos);
297 cur.setCurrentFont();
302 Inset * InsetText::editXY(Cursor & cur, int x, int y)
304 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
308 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
310 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
313 // See bug #9042, for instance.
315 // Force any new text to latex_language FIXME: This
316 // should only be necessary in constructor, but new
317 // paragraphs that are created by pressing enter at
318 // the start of an existing paragraph get the buffer
319 // language and not latex_language, so we take this
320 // brute force approach.
321 cur.current_font.setLanguage(latex_language);
322 cur.real_current_font.setLanguage(latex_language);
326 switch (cmd.action()) {
328 case LFUN_CLIPBOARD_PASTE:
329 case LFUN_SELECTION_PASTE:
330 case LFUN_PRIMARY_SELECTION_PASTE:
331 text_.dispatch(cur, cmd);
332 // If we we can only store plain text, we must reset all
334 // FIXME: Change only the pasted paragraphs
338 case LFUN_INSET_SPLIT:
339 case LFUN_INSET_DISSOLVE: {
340 bool const main_inset = text_.isMainText();
341 bool const target_inset = cmd.argument().empty()
342 || cmd.getArg(0) == insetName(lyxCode());
344 if (!main_inset && target_inset) {
345 UndoGroupHelper ugh(&buffer());
346 // Text::dissolveInset assumes that the cursor
347 // is inside the Inset.
348 if (&cur.inset() != this) {
350 cur.pushBackward(*this);
352 text_.dispatch(cur, cmd);
359 text_.dispatch(cur, cmd);
362 if (!cur.result().dispatched())
363 Inset::doDispatch(cur, cmd);
367 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
368 FuncStatus & status) const
370 switch (cmd.action()) {
371 case LFUN_INSET_SPLIT:
372 case LFUN_INSET_DISSOLVE: {
373 bool const main_inset = text_.isMainText();
374 bool const target_inset = cmd.argument().empty()
375 || cmd.getArg(0) == insetName(lyxCode());
378 status.setEnabled(!main_inset);
382 case LFUN_ARGUMENT_INSERT: {
383 string const arg = cmd.getArg(0);
385 status.setEnabled(false);
388 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
389 return text_.getStatus(cur, cmd, status);
391 Layout::LaTeXArgMap args = getLayout().args();
392 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
393 if (lait != args.end()) {
394 status.setEnabled(true);
395 for (Paragraph const & par : paragraphs())
396 for (auto const & table : par.insetList())
397 if (InsetArgument const * ins = table.inset->asInsetArgument())
398 if (ins->name() == arg) {
399 // we have this already
400 status.setEnabled(false);
404 status.setEnabled(false);
409 // Dispatch only to text_ if the cursor is inside
410 // the text_. It is not for context menus (bug 5797).
412 if (cur.text() == &text_)
413 ret = text_.getStatus(cur, cmd, status);
416 ret = Inset::getStatus(cur, cmd, status);
422 void InsetText::fixParagraphsFont()
424 Font font(inherit_font, buffer().params().language);
425 font.setLanguage(latex_language);
426 ParagraphList::iterator par = paragraphs().begin();
427 ParagraphList::iterator const end = paragraphs().end();
429 if (par->isPassThru())
430 par->resetFonts(font);
431 if (!par->allowParagraphCustomization())
432 par->params().clear();
438 // bool InsetText::isChanged() const
440 // ParagraphList::const_iterator pit = paragraphs().begin();
441 // ParagraphList::const_iterator end = paragraphs().end();
442 // for (; pit != end; ++pit) {
443 // if (pit->isChanged())
450 void InsetText::setChange(Change const & change)
452 ParagraphList::iterator pit = paragraphs().begin();
453 ParagraphList::iterator end = paragraphs().end();
454 for (; pit != end; ++pit) {
455 pit->setChange(change);
460 void InsetText::acceptChanges()
462 text_.acceptChanges();
466 void InsetText::rejectChanges()
468 text_.rejectChanges();
472 void InsetText::validate(LaTeXFeatures & features) const
474 features.useInsetLayout(getLayout());
475 for (Paragraph const & p : paragraphs())
476 p.validate(features);
480 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
482 // This implements the standard way of handling the LaTeX
483 // output of a text inset, either a command or an
484 // environment. Standard collapsible insets should not
485 // redefine this, non-standard ones may call this.
486 InsetLayout const & il = getLayout();
487 if (il.forceOwnlines())
489 bool needendgroup = false;
490 if (!il.latexname().empty()) {
491 if (il.latextype() == InsetLaTeXType::COMMAND) {
493 // FIXME \protect should only be used for fragile
494 // commands, but we do not provide this information yet.
495 if (hasCProtectContent(runparams.moving_arg)) {
496 if (contains(runparams.active_chars, '^')) {
497 // cprotect relies on ^ being on catcode 7
498 os << "\\begingroup\\catcode`\\^=7";
502 } else if (runparams.moving_arg)
504 os << '\\' << from_utf8(il.latexname());
505 if (!il.latexargs().empty())
506 getArgs(os, runparams);
507 if (!il.latexparam().empty())
508 os << from_utf8(il.latexparam());
510 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
515 if (runparams.lastid != -1)
516 os.texrow().start(runparams.lastid,
518 os << "\\begin{" << from_utf8(il.latexname()) << "}";
519 if (!il.latexargs().empty())
520 getArgs(os, runparams);
521 if (!il.latexparam().empty())
522 os << from_utf8(il.latexparam());
526 if (!il.latexargs().empty())
527 getArgs(os, runparams);
528 if (!il.latexparam().empty())
529 os << from_utf8(il.latexparam());
532 if (!il.leftdelim().empty())
533 os << il.leftdelim();
535 OutputParams rp = runparams;
538 if (il.isNeedProtect())
539 rp.moving_arg = true;
540 if (il.isNeedMBoxProtect())
542 if (!il.passThruChars().empty())
543 rp.pass_thru_chars += il.passThruChars();
544 if (!il.newlineCmd().empty())
545 rp.newlinecmd = il.newlineCmd();
547 rp.par_end = paragraphs().size();
549 // Output the contents of the inset
550 latexParagraphs(buffer(), text_, os, rp);
551 runparams.encoding = rp.encoding;
552 // Pass the post_macros upstream
553 runparams.post_macro = rp.post_macro;
554 // These need to be passed upstream as well
555 runparams.need_maketitle = rp.need_maketitle;
556 runparams.have_maketitle = rp.have_maketitle;
558 if (!il.rightdelim().empty())
559 os << il.rightdelim();
561 if (!il.latexname().empty()) {
562 if (il.latextype() == InsetLaTeXType::COMMAND) {
564 if (!il.postcommandargs().empty())
565 getArgs(os, runparams, true);
568 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
569 // A comment environment doesn't need a % before \n\end
570 if (il.isDisplay() || runparams.inComment)
574 os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
576 os.protectSpace(true);
579 if (il.forceOwnlines())
584 int InsetText::plaintext(odocstringstream & os,
585 OutputParams const & runparams, size_t max_length) const
587 ParagraphList::const_iterator beg = paragraphs().begin();
588 ParagraphList::const_iterator end = paragraphs().end();
589 ParagraphList::const_iterator it = beg;
590 bool ref_printed = false;
592 for (; it != end; ++it) {
595 if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
598 odocstringstream oss;
599 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
600 docstring const str = oss.str();
602 // FIXME: len is not computed fully correctly; in principle,
603 // we have to count the characters after the last '\n'
605 if (os.str().size() >= max_length)
613 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
615 docbook(xs, rp, WriteEverything);
619 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
621 // Always output all the paragraphs.
622 OutputParams runparams = rp;
623 runparams.par_begin = 0;
624 runparams.par_end = text().paragraphs().size();
627 xs.startDivision(false);
628 docbookParagraphs(text_, buffer(), xs, runparams);
633 InsetLayout const &il = getLayout();
635 // Maybe this is an <info> paragraph that should not be generated
636 // at all (i.e. right now, its place is somewhere else, typically outside
637 // the current paragraph).
638 if (!rp.docbook_generate_info && il.docbookininfo() != "never")
641 // Maybe this inset must be rendered before being output.
642 if (il.docbookrenderasimage()) {
643 docbookRenderAsImage(xs, runparams, opts);
647 // If none of the special cases before apply, output the inset.
648 docbookText(xs, runparams, opts);
652 void InsetText::docbookRenderAsImage(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
654 LASSERT(getLayout().docbookrenderasimage(), return);
656 // Generate the LaTeX code to compile in order to get the image.
657 // This code actually does the same as an InsetPreview, but without
659 // Also, the image must be generated before the DocBook output is finished,
660 // unlike a preview that is not immediately required for display.
661 docstring const latex_snippet = insetToLaTeXSnippet(&buffer(), this);
662 std::string const snippet = support::trim(to_utf8(latex_snippet));
663 // TODO: no real support for Unicode. This code is very similar to RenderPreview::addPreview, the same gotcha applies.
665 graphics::PreviewLoader* loader = buffer().loader();
666 loader->add(snippet);
667 loader->startLoading(true); // Generate the image and wait until done.
668 graphics::PreviewImage const * img = loader->preview(snippet);
669 LASSERT(img != nullptr, return);
670 support::FileName const & filename = img->filename();
672 // Copy the image into the right folder.
673 rp.exportdata->addExternalFile("docbook", filename, filename.onlyFileName());
675 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
676 // Start writing the DocBook code for the image.
677 xs << xml::StartTag("mediaobject")
680 // Output the rendered inset.
681 xs << xml::StartTag("imageobject")
683 << xml::StartTag("imagedata", std::string("fileref='") + filename.onlyFileName() + "'")
685 << xml::EndTag("imageobject")
688 // Output the raw content.
689 xs << xml::StartTag("textobject")
691 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
692 docbookText(xs, rp, opts);
693 xs << xml::EndTag("programlisting")
695 << xml::EndTag("textobject")
698 xs << xml::EndTag("mediaobject")
703 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
705 InsetLayout const &il = getLayout();
706 OutputParams runparams = rp;
708 // In some cases, the input parameters must be overridden for outer tags.
709 bool writeOuterTag = opts & WriteOuterTag;
711 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
712 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
713 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
714 auto parSize = (size_t) par.size();
715 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
717 writeOuterTag = !allBibitems;
720 // Detect arguments that should be output before/after the paragraph.
721 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
722 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
723 std::set<InsetArgument const *> prependedArguments;
724 for (auto const & par : paragraphs()) {
725 for (pos_type i = 0; i < par.size(); ++i) {
726 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
727 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
728 if (arg->docbookargumentbeforemaintag())
729 prependedArguments.insert(par.getInset(i)->asInsetArgument());
734 std::set<InsetArgument const *> appendedArguments;
735 for (auto const & par : paragraphs()) {
736 for (pos_type i = 0; i < par.size(); ++i) {
737 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
738 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
739 if (arg->docbookargumentaftermaintag())
740 appendedArguments.insert(par.getInset(i)->asInsetArgument());
745 // Start outputting this inset.
746 // - First, wrapper around the inset and its main tag.
748 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
749 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
751 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
752 docstring attrs = docstring();
753 if (!il.docbookattr().empty())
754 attrs += from_ascii(il.docbookattr());
755 if (il.docbooktag() == "link")
756 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
757 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
760 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
761 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
764 // - Think about the arguments before the paragraph.
765 OutputParams np = runparams;
766 np.docbook_in_par = true;
767 for (auto const & arg : prependedArguments)
768 arg->docbook(xs, np);
770 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
771 runparams.docbook_prepended_arguments = std::move(prependedArguments);
772 runparams.docbook_appended_arguments = appendedArguments;
774 // - Deal with the first item.
775 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
777 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
778 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
780 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
781 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
784 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
786 // With respect to XHTML, paragraphs are still allowed here.
787 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
788 runparams.docbook_make_pars = false;
790 runparams.pass_thru = true;
792 // - Write the main content of the inset.
793 xs.startDivision(false);
794 docbookParagraphs(text_, buffer(), xs, runparams);
797 // - Think about the arguments after the paragraph.
798 for (auto const & arg : appendedArguments)
799 arg->docbook(xs, np);
801 // - Close the required tags.
803 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
804 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
806 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
807 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
809 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
810 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
812 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
813 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
815 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
816 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
821 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
823 return insetAsXHTML(xs, runparams, WriteEverything);
828 // There are cases where we may need to close open fonts and such
829 // and then re-open them when we are done. This would be the case, e.g.,
830 // if we were otherwise about to write:
831 // <em>word <div class='foot'>footnote text.</div> emph</em>
832 // The problem isn't so much that the footnote text will get emphasized:
833 // we can handle that with CSS. The problem is that this is invalid XHTML.
834 // One solution would be to make the footnote <span>, but the problem is
835 // completely general, and so we'd have to make absolutely everything into
836 // span. What I think will work is to check if we're about to write "div" and,
837 // if so, try to close fonts, etc.
838 // There are probably limits to how well we can do here, though, and we will
839 // have to rely upon users not putting footnotes inside noun-type insets.
840 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
841 XHTMLOptions opts) const
843 // we will always want to output all our paragraphs when we are
845 OutputParams runparams = rp;
846 runparams.par_begin = 0;
847 runparams.par_end = text().paragraphs().size();
850 xs.startDivision(false);
851 xhtmlParagraphs(text_, buffer(), xs, runparams);
856 InsetLayout const & il = getLayout();
857 if (opts & WriteOuterTag)
858 xs << xml::StartTag(il.htmltag(), il.htmlattr());
860 if ((opts & WriteLabel) && !il.counter().empty()) {
861 BufferParams const & bp = buffer().masterBuffer()->params();
862 Counters & cntrs = bp.documentClass().counters();
863 cntrs.step(il.counter(), OutputUpdate);
864 // FIXME: translate to paragraph language
865 if (!il.htmllabel().empty()) {
866 docstring const lbl =
867 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
868 // FIXME is this check necessary?
870 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
872 xs << xml::EndTag(il.htmllabeltag());
877 if (opts & WriteInnerTag)
878 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
880 // we will eventually lose information about the containing inset
881 if (!allowMultiPar() || opts == JustText)
882 runparams.html_make_pars = false;
884 runparams.pass_thru = true;
886 xs.startDivision(false);
887 xhtmlParagraphs(text_, buffer(), xs, runparams);
890 if (opts & WriteInnerTag)
891 xs << xml::EndTag(il.htmlinnertag());
893 if (opts & WriteOuterTag)
894 xs << xml::EndTag(il.htmltag());
900 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
901 bool const post) const
903 OutputParams runparams = runparams_in;
904 runparams.local_font =
905 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
907 runparams.pass_thru = true;
909 latexArgInsetsForParent(paragraphs(), os, runparams,
910 getLayout().postcommandargs(), "post:");
912 latexArgInsetsForParent(paragraphs(), os, runparams,
913 getLayout().latexargs());
917 void InsetText::cursorPos(BufferView const & bv,
918 CursorSlice const & sl, bool boundary, int & x, int & y) const
920 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
921 y = bv.textMetrics(&text_).cursorY(sl, boundary);
925 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
928 Paragraph & first = paragraphs().front();
929 for (unsigned int i = 0; i < data.length(); ++i)
930 first.insertChar(i, data[i], font, trackChanges);
934 void InsetText::setDrawFrame(bool flag)
940 ColorCode InsetText::frameColor() const
946 void InsetText::setFrameColor(ColorCode col)
952 void InsetText::appendParagraphs(ParagraphList & plist)
954 // There is little we can do here to keep track of changes.
955 // As of 2006/10/20, appendParagraphs is used exclusively by
956 // LyXTabular::setMultiColumn. In this context, the paragraph break
957 // is lost irreversibly and the appended text doesn't really change
959 ParagraphList & pl = paragraphs();
961 ParagraphList::iterator pit = plist.begin();
962 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
964 mergeParagraph(buffer().params(), pl,
965 distance(pl.begin(), ins) - 1);
967 ParagraphList::iterator const pend = plist.end();
968 for (; pit != pend; ++pit)
973 void InsetText::addPreview(DocIterator const & text_inset_pos,
974 graphics::PreviewLoader & loader) const
976 ParagraphList::const_iterator pit = paragraphs().begin();
977 ParagraphList::const_iterator pend = paragraphs().end();
980 DocIterator inset_pos = text_inset_pos;
981 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
983 for (; pit != pend; ++pit, ++pidx) {
984 InsetList::const_iterator it = pit->insetList().begin();
985 InsetList::const_iterator end = pit->insetList().end();
986 inset_pos.pit() = pidx;
987 for (; it != end; ++it) {
988 inset_pos.pos() = it->pos;
989 it->inset->addPreview(inset_pos, loader);
995 ParagraphList const & InsetText::paragraphs() const
997 return text_.paragraphs();
1001 ParagraphList & InsetText::paragraphs()
1003 return text_.paragraphs();
1007 bool InsetText::hasCProtectContent(bool fragile) const
1009 fragile |= getLayout().isNeedProtect();
1010 ParagraphList const & pars = paragraphs();
1011 pit_type pend = pit_type(paragraphs().size());
1012 for (pit_type pit = 0; pit != pend; ++pit) {
1013 Paragraph const & par = pars[size_type(pit)];
1014 if (par.needsCProtection(fragile))
1021 bool InsetText::insetAllowed(InsetCode code) const
1024 // Arguments, (plain) quotes and counter insets
1025 // are also allowed in PassThru insets
1031 return !isPassThru();
1036 bool InsetText::allowSpellCheck() const
1038 return getLayout().spellcheck() && !getLayout().isPassThru();
1042 bool InsetText::allowMultiPar() const
1044 return getLayout().isMultiPar();
1048 bool InsetText::forcePlainLayout(idx_type) const
1050 return getLayout().forcePlainLayout();
1054 bool InsetText::allowParagraphCustomization(idx_type) const
1056 return getLayout().allowParagraphCustomization();
1060 bool InsetText::forceLocalFontSwitch() const
1062 return getLayout().forceLocalFontSwitch();
1066 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1068 ParIterator it2 = it;
1070 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1071 if (producesOutput()) {
1072 InsetLayout const & il = getLayout();
1073 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1074 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1076 // LYXERR0("Entering " << name());
1077 cnt.clearLastLayout();
1078 // FIXME cnt.saveLastCounter()?
1080 buffer().updateBuffer(it2, utype, deleted);
1082 // LYXERR0("Exiting " << name());
1083 cnt.restoreLastLayout();
1084 // FIXME cnt.restoreLastCounter()?
1086 // Record if this inset is embedded in a title layout
1087 // This is needed to decide when \maketitle is output.
1088 intitle_context_ = it.paragraph().layout().intitle;
1089 // Also check embedding layouts
1090 size_t const n = it.depth();
1091 for (size_t i = 0; i < n; ++i) {
1092 if (it[i].paragraph().layout().intitle) {
1093 intitle_context_ = true;
1098 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1099 // Note that we do not need to call:
1100 // tclass.counters().clearLastLayout()
1101 // since we are saving and restoring the existing counters, etc.
1102 Counters savecnt = tclass.counters();
1103 tclass.counters().reset();
1104 // we need float information even in note insets (#9760)
1105 tclass.counters().current_float(savecnt.current_float());
1106 tclass.counters().isSubfloat(savecnt.isSubfloat());
1107 buffer().updateBuffer(it2, utype, deleted);
1108 tclass.counters() = move(savecnt);
1113 void InsetText::toString(odocstream & os) const
1115 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1119 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1120 bool const shorten) const
1122 if (!getLayout().isInToc())
1124 text().forOutliner(os, maxlen, shorten);
1128 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1129 UpdateType utype, TocBackend & backend) const
1131 DocIterator dit = cdit;
1132 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1133 iterateForToc(dit, output_active, utype, backend);
1137 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1138 UpdateType utype, TocBackend & backend) const
1140 DocIterator dit = cdit;
1141 // This also ensures that any document has a table of contents
1142 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1144 BufferParams const & bufparams = buffer_->params();
1145 int const min_toclevel = bufparams.documentClass().min_toclevel();
1146 // we really should have done this before we got here, but it
1147 // can't hurt too much to do it again
1148 bool const doing_output = output_active && producesOutput();
1150 // For each paragraph,
1151 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1152 // paragraphs as needed.
1153 // * Traverse its insets and let them add their toc items
1154 // * Compute the main table of contents (this is hardcoded)
1155 // * Add the list of changes
1156 ParagraphList const & pars = paragraphs();
1157 pit_type pend = paragraphs().size();
1158 // Record pairs {start,end} of where a toc item was opened for a paragraph
1159 // and where it must be closed
1160 stack<pair<pit_type, pit_type>> addtotoc_stack;
1162 for (pit_type pit = 0; pit != pend; ++pit) {
1163 Paragraph const & par = pars[pit];
1167 // Custom AddToToc in paragraph layouts (i.e. theorems)
1168 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1170 openAddToTocForParagraph(pit, dit, output_active, backend);
1171 addtotoc_stack.push({pit, end});
1174 // If we find an InsetArgument that is supposed to provide the TOC caption,
1175 // we'll save it for use later.
1176 InsetArgument const * arginset = nullptr;
1177 for (auto const & table : par.insetList()) {
1178 dit.pos() = table.pos;
1179 table.inset->addToToc(dit, doing_output, utype, backend);
1180 if (InsetArgument const * x = table.inset->asInsetArgument())
1181 if (x->isTocCaption())
1185 // End custom AddToToc in paragraph layouts
1186 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1187 // execute the closing function
1188 closeAddToTocForParagraph(addtotoc_stack.top().first,
1189 addtotoc_stack.top().second, backend);
1190 addtotoc_stack.pop();
1193 // now the toc entry for the paragraph in the main table of contents
1194 int const toclevel = text().getTocLevel(pit);
1195 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1196 // insert this into the table of contents
1197 docstring tocstring;
1198 int const length = (doing_output && utype == OutputUpdate) ?
1199 INT_MAX : TOC_ENTRY_LENGTH;
1201 tocstring = par.labelString();
1202 if (!tocstring.empty())
1204 arginset->text().forOutliner(tocstring, length);
1206 par.forOutliner(tocstring, length);
1208 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1209 tocstring, doing_output));
1212 // And now the list of changes.
1213 par.addChangesToToc(dit, buffer(), doing_output, backend);
1218 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1219 DocIterator const & dit,
1221 TocBackend & backend) const
1223 Paragraph const & par = paragraphs()[pit];
1224 TocBuilder & b = backend.builder(par.layout().tocType());
1225 docstring const & label = par.labelString();
1226 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1227 return text().lastInSequence(pit);
1231 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1232 TocBackend & backend) const
1234 Paragraph const & par = paragraphs()[start];
1235 TocBuilder & b = backend.builder(par.layout().tocType());
1236 if (par.layout().isTocCaption()) {
1238 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1239 b.argumentItem(str);
1245 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1247 if (buffer().isClean())
1248 return Inset::notifyCursorLeaves(old, cur);
1250 // find text inset in old cursor
1251 Cursor insetCur = old;
1252 int scriptSlice = insetCur.find(this);
1253 // we can try to continue here. returning true means
1254 // the cursor is "now" invalid. which it was.
1255 LASSERT(scriptSlice != -1, return true);
1256 insetCur.cutOff(scriptSlice);
1257 LASSERT(&insetCur.inset() == this, return true);
1259 // update the old paragraph's words
1260 insetCur.paragraph().updateWords();
1262 return Inset::notifyCursorLeaves(old, cur);
1266 bool InsetText::completionSupported(Cursor const & cur) const
1268 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1269 return text_.completionSupported(cur);
1273 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1275 return completionSupported(cur);
1279 bool InsetText::automaticInlineCompletion() const
1281 return lyxrc.completion_inline_text;
1285 bool InsetText::automaticPopupCompletion() const
1287 return lyxrc.completion_popup_text;
1291 bool InsetText::showCompletionCursor() const
1293 return lyxrc.completion_cursor_text &&
1294 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1298 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1300 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1304 docstring InsetText::completionPrefix(Cursor const & cur) const
1306 if (!completionSupported(cur))
1308 return text_.completionPrefix(cur);
1312 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1315 if (!completionSupported(cur))
1318 return text_.insertCompletion(cur, s, finished);
1322 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1323 Dimension & dim) const
1325 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1326 tm.completionPosAndDim(cur, x, y, dim);
1330 string InsetText::contextMenu(BufferView const &, int, int) const
1332 string context_menu = contextMenuName();
1333 if (context_menu != InsetText::contextMenuName())
1334 context_menu += ";" + InsetText::contextMenuName();
1335 return context_menu;
1339 string InsetText::contextMenuName() const
1341 return "context-edit";
1345 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1347 OutputParams rp(&buffer().params().encoding());
1348 rp.for_tooltip = true;
1349 odocstringstream oss;
1352 ParagraphList::const_iterator beg = paragraphs().begin();
1353 ParagraphList::const_iterator end = paragraphs().end();
1354 ParagraphList::const_iterator it = beg;
1355 bool ref_printed = false;
1357 for (; it != end; ++it) {
1360 if ((*it).isRTL(buffer().params()))
1361 oss << "<div dir=\"rtl\">";
1362 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1363 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1366 docstring str = oss.str();
1368 str += from_ascii("\n\n") + _("[contains tracked changes]");
1369 support::truncateWithEllipsis(str, len);
1374 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1376 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1380 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1382 // Nested cprotect content needs \cprotect
1384 if (producesOutput() && hasCProtectContent(fragile))
1387 // Environments generally need cprotection in fragile context
1388 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1391 if (!getLayout().needsCProtect())
1394 // Environments and "no latex" types (e.g., knitr chunks)
1395 // need cprotection regardless the content
1396 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1399 // If the inset does not produce output (e.g. Note or Branch),
1400 // we can ignore the contained paragraphs
1401 if (!producesOutput())
1404 // Commands need cprotection if they contain specific chars
1405 int const nchars_escape = 9;
1406 static char_type const chars_escape[nchars_escape] = {
1407 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1409 ParagraphList const & pars = paragraphs();
1410 pit_type pend = pit_type(paragraphs().size());
1412 for (pit_type pit = 0; pit != pend; ++pit) {
1413 Paragraph const & par = pars[size_type(pit)];
1414 if (par.needsCProtection(fragile))
1416 docstring const par_str = par.asString();
1417 for (int k = 0; k < nchars_escape; k++) {
1418 if (contains(par_str, chars_escape[k]))