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"
75 #include <QCryptographicHash>
79 using namespace lyx::support;
84 /////////////////////////////////////////////////////////////////////
86 InsetText::InsetText(Buffer * buf, UsePlain type)
87 : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
88 frame_color_(Color_insetframe),
89 text_(this, type == DefaultLayout)
94 InsetText::InsetText(InsetText const & in)
95 : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
96 intitle_context_(false), frame_color_(in.frame_color_),
102 void InsetText::setBuffer(Buffer & buf)
104 ParagraphList::iterator end = paragraphs().end();
105 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
106 it->setInsetBuffers(buf);
107 Inset::setBuffer(buf);
111 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
113 text_.setMacrocontextPosition(pos);
115 ParagraphList::const_iterator pit = paragraphs().begin();
116 ParagraphList::const_iterator pend = paragraphs().end();
117 for (; pit != pend; ++pit) {
118 InsetList::const_iterator iit = pit->insetList().begin();
119 InsetList::const_iterator end = pit->insetList().end();
120 for (; iit != end; ++iit) {
121 if (InsetText * txt = iit->inset->asInsetText()) {
122 DocIterator ppos(pos);
123 ppos.push_back(CursorSlice(*txt));
124 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
131 void InsetText::clear()
133 ParagraphList & pars = paragraphs();
134 LBUFERR(!pars.empty());
136 // This is a gross hack...
137 Layout const & old_layout = pars.begin()->layout();
140 pars.push_back(Paragraph());
141 pars.begin()->setInsetOwner(this);
142 pars.begin()->setLayout(old_layout);
146 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
148 TextMetrics const & tm = bv.textMetrics(&text_);
149 Dimension dim = tm.dim();
150 dim.wid += leftOffset(&bv) + rightOffset(&bv);
151 dim.des += bottomOffset(&bv);
152 dim.asc += topOffset(&bv);
157 void InsetText::write(ostream & os) const
164 void InsetText::read(Lexer & lex)
168 // delete the initial paragraph
169 Paragraph oldpar = *paragraphs().begin();
170 paragraphs().clear();
172 lex.setContext("InsetText::read");
173 bool res = text_.read(lex, errorList, this);
176 lex.printError("Missing \\end_inset at this point. ");
179 // ensure we have at least one paragraph.
180 if (paragraphs().empty())
181 paragraphs().push_back(oldpar);
182 // Force default font, if so requested
183 // This avoids paragraphs in buffer language that would have a
184 // foreign language after a document language change, and it ensures
185 // that all new text in ERT and similar gets the "latex" language,
186 // since new text inherits the language from the last position of the
187 // existing text. As a side effect this makes us also robust against
188 // bugs in LyX that might lead to font changes in ERT in .lyx files.
193 void InsetText::setOuterFont(BufferView & bv, FontInfo const & outer) const
195 TextMetrics & tm = bv.textMetrics(&text_);
196 FontInfo tmpfont = getFont();
197 tmpfont.realize(outer);
198 tm.font_.fontInfo() = tmpfont;
202 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
204 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
206 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
208 int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
209 mi.base.textwidth -= horiz_offset;
211 // Remember the full outer font
212 setOuterFont(*mi.base.bv, mi.base.font);
213 // and use it in these metrics computation.
214 mi.base.font = tm.font_.fontInfo();
216 // This can happen when a layout has a left and right margin,
217 // and the view is made very narrow. We can't do better than
218 // to draw it partly out of view (bug 5890).
219 if (mi.base.textwidth < 1)
220 mi.base.textwidth = 1;
223 tm.metrics(mi, dim, mi.base.textwidth);
226 mi.base.textwidth += horiz_offset;
227 dim.asc += topOffset(mi.base.bv);
228 dim.des += bottomOffset(mi.base.bv);
229 dim.wid += horiz_offset;
233 void InsetText::draw(PainterInfo & pi, int x, int y) const
235 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
237 int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
238 int const w = tm.width() + (horiz_offset - horiz_offset / 2);
239 int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
240 int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
241 int const xframe = x + leftOffset(pi.base.bv) / 2;
242 bool change_drawn = false;
244 pi.pain.fillRectangle(xframe, yframe, w, h,
245 pi.backgroundColor(this));
248 Changer dummy = changeVar(pi.background_color,
249 pi.backgroundColor(this, false));
250 // The change tracking cue must not be inherited
251 Changer dummy2 = changeVar(pi.change, Change());
252 tm.draw(pi, x + leftOffset(pi.base.bv), y);
256 // Change color of the frame in tracked changes, like for tabulars.
257 // Only do so if the color is not custom. But do so even if RowPainter
258 // handles the strike-through already.
260 if (pi.change.changed()
261 // Originally, these are the colors with role Text, from role() in
262 // ColorCache.cpp. The code is duplicated to avoid depending on Qt
263 // types, and also maybe it need not match in the future.
264 && (frameColor() == Color_foreground
265 || frameColor() == Color_cursor
266 || frameColor() == Color_preview
267 || frameColor() == Color_tabularline
268 || frameColor() == Color_previewframe)) {
269 c = pi.change.color();
273 pi.pain.rectangle(xframe, yframe, w, h, c);
276 if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
277 // Do not draw the change tracking cue if already done by RowPainter and
278 // do not draw the cue for INSERTED if the information is already in the
279 // color of the frame
280 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
284 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
286 pit_type const pit = front ? 0 : paragraphs().size() - 1;
287 pos_type pos = front ? 0 : paragraphs().back().size();
289 // if visual information is not to be ignored, move to extreme right/left
290 if (entry_from != ENTRY_DIRECTION_IGNORE) {
291 Cursor temp_cur = cur;
292 temp_cur.pit() = pit;
293 temp_cur.pos() = pos;
294 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
295 pos = temp_cur.pos();
298 cur.top().setPitPos(pit, pos);
299 cur.setCurrentFont();
304 Inset * InsetText::editXY(Cursor & cur, int x, int y)
306 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
310 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
312 LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
315 // See bug #9042, for instance.
317 // Force any new text to latex_language FIXME: This
318 // should only be necessary in constructor, but new
319 // paragraphs that are created by pressing enter at
320 // the start of an existing paragraph get the buffer
321 // language and not latex_language, so we take this
322 // brute force approach.
323 cur.current_font.setLanguage(latex_language);
324 cur.real_current_font.setLanguage(latex_language);
328 switch (cmd.action()) {
330 case LFUN_CLIPBOARD_PASTE:
331 case LFUN_SELECTION_PASTE:
332 case LFUN_PRIMARY_SELECTION_PASTE:
333 text_.dispatch(cur, cmd);
334 // If we we can only store plain text, we must reset all
336 // FIXME: Change only the pasted paragraphs
340 case LFUN_INSET_SPLIT:
341 case LFUN_INSET_DISSOLVE: {
342 bool const main_inset = text_.isMainText();
343 bool const target_inset = cmd.argument().empty()
344 || cmd.getArg(0) == insetName(lyxCode());
346 if (!main_inset && target_inset) {
347 UndoGroupHelper ugh(&buffer());
348 // Text::dissolveInset assumes that the cursor
349 // is inside the Inset.
350 if (&cur.inset() != this) {
352 cur.pushBackward(*this);
354 text_.dispatch(cur, cmd);
361 text_.dispatch(cur, cmd);
364 if (!cur.result().dispatched())
365 Inset::doDispatch(cur, cmd);
369 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
370 FuncStatus & status) const
372 switch (cmd.action()) {
373 case LFUN_INSET_SPLIT:
374 case LFUN_INSET_DISSOLVE: {
375 bool const main_inset = text_.isMainText();
376 bool const target_inset = cmd.argument().empty()
377 || cmd.getArg(0) == insetName(lyxCode());
380 status.setEnabled(!main_inset);
384 case LFUN_ARGUMENT_INSERT: {
385 string const arg = cmd.getArg(0);
387 status.setEnabled(false);
390 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
391 return text_.getStatus(cur, cmd, status);
393 Layout::LaTeXArgMap args = getLayout().args();
394 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
395 if (lait != args.end()) {
396 status.setEnabled(true);
397 for (Paragraph const & par : paragraphs())
398 for (auto const & table : par.insetList())
399 if (InsetArgument const * ins = table.inset->asInsetArgument())
400 if (ins->name() == arg) {
401 // we have this already
402 status.setEnabled(false);
406 status.setEnabled(false);
411 // Dispatch only to text_ if the cursor is inside
412 // the text_. It is not for context menus (bug 5797).
414 if (cur.text() == &text_)
415 ret = text_.getStatus(cur, cmd, status);
418 ret = Inset::getStatus(cur, cmd, status);
424 void InsetText::fixParagraphsFont()
426 Font font(inherit_font, buffer().params().language);
427 font.setLanguage(latex_language);
428 ParagraphList::iterator par = paragraphs().begin();
429 ParagraphList::iterator const end = paragraphs().end();
431 if (par->isPassThru())
432 par->resetFonts(font);
433 if (!par->allowParagraphCustomization())
434 par->params().clear();
440 // bool InsetText::isChanged() const
442 // ParagraphList::const_iterator pit = paragraphs().begin();
443 // ParagraphList::const_iterator end = paragraphs().end();
444 // for (; pit != end; ++pit) {
445 // if (pit->isChanged())
452 void InsetText::setChange(Change const & change)
454 ParagraphList::iterator pit = paragraphs().begin();
455 ParagraphList::iterator end = paragraphs().end();
456 for (; pit != end; ++pit) {
457 pit->setChange(change);
462 void InsetText::acceptChanges()
464 text_.acceptChanges();
468 void InsetText::rejectChanges()
470 text_.rejectChanges();
474 void InsetText::validate(LaTeXFeatures & features) const
476 features.useInsetLayout(getLayout());
477 for (Paragraph const & p : paragraphs())
478 p.validate(features);
482 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
484 // This implements the standard way of handling the LaTeX
485 // output of a text inset, either a command or an
486 // environment. Standard collapsible insets should not
487 // redefine this, non-standard ones may call this.
488 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 loader->add(snippet);
669 loader->startLoading(true); // Generate the image and wait until done.
670 graphics::PreviewImage const * img = loader->preview(snippet);
671 LASSERT(img != nullptr, return);
672 support::FileName const & filename = img->filename();
674 // Use a file name that is only determined by the LaTeX code: the name of
675 // the snippet is more or less random (i.e., if the user generates the file
676 // several times, they will have a clutter of preview files).
677 // Hence: use a cryptographic hash of the snippet. If the snippet changes,
678 // the file name will change a lot; two snippets are unlikely to have the
679 // same hash (by design of cryptographic hash functions). Computing a hash
680 // is typically slow, but extremely fast compared to compilation of the
681 // preview and image rendering.
682 QString snippetQ = QString(snippet.c_str());
683 #if QT_VERSION >= 0x050000
684 QByteArray hash = QCryptographicHash::hash(snippetQ.toLocal8Bit(), QCryptographicHash::Sha256);
686 QByteArray hash = QCryptographicHash::hash(snippetQ.toLocal8Bit(), QCryptographicHash::Sha1);
688 auto newFileBase = QString(hash.toBase64())
692 std::string newFileName = "lyx_" + newFileBase.toStdString() + "." + filename.extension();
694 // Copy the image into the right folder.
695 rp.exportdata->addExternalFile("docbook5", filename, newFileName);
697 // TODO: deal with opts. What exactly is the WriterOuterTag here, for instance?
698 // Start writing the DocBook code for the image.
699 xs << xml::StartTag("mediaobject")
702 // Output the rendered inset.
703 xs << xml::StartTag("imageobject")
705 << xml::CompTag("imagedata", std::string("fileref='") + newFileName + "'")
707 << xml::EndTag("imageobject")
710 // Output the raw content.
711 xs << xml::StartTag("textobject")
713 << xml::StartTag("programlisting", "language='latex' role='" + getLayout().latexname() + "'");
714 docbookText(xs, rp, opts);
715 xs << xml::EndTag("programlisting")
717 << xml::EndTag("textobject")
720 xs << xml::EndTag("mediaobject");
724 void InsetText::docbookText(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
726 InsetLayout const &il = getLayout();
727 OutputParams runparams = rp;
729 // In some cases, the input parameters must be overridden for outer tags.
730 bool writeOuterTag = opts & WriteOuterTag;
732 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
733 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
734 auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
735 auto parSize = (size_t) par.size();
736 return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
738 writeOuterTag = !allBibitems;
741 // Detect arguments that should be output before/after the paragraph.
742 // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
743 // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
744 std::set<InsetArgument const *> prependedArguments;
745 for (auto const & par : paragraphs()) {
746 for (pos_type i = 0; i < par.size(); ++i) {
747 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
748 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
749 if (arg->docbookargumentbeforemaintag())
750 prependedArguments.insert(par.getInset(i)->asInsetArgument());
755 std::set<InsetArgument const *> appendedArguments;
756 for (auto const & par : paragraphs()) {
757 for (pos_type i = 0; i < par.size(); ++i) {
758 if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
759 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
760 if (arg->docbookargumentaftermaintag())
761 appendedArguments.insert(par.getInset(i)->asInsetArgument());
766 // Start outputting this inset.
767 // - First, wrapper around the inset and its main tag.
769 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
770 xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
772 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
773 docstring attrs = docstring();
774 if (!il.docbookattr().empty())
775 attrs += from_ascii(il.docbookattr());
776 if (il.docbooktag() == "link")
777 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
778 xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
781 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
782 xml::openTag(xs, il.docbookinnertag(), il.docbookinnerattr(), il.docbookinnertagtype());
785 // - Think about the arguments before the paragraph.
786 OutputParams np = runparams;
787 np.docbook_in_par = true;
788 for (auto const & arg : prependedArguments)
789 arg->docbook(xs, np);
791 // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
792 runparams.docbook_prepended_arguments = std::move(prependedArguments);
793 runparams.docbook_appended_arguments = appendedArguments;
795 // - Deal with the first item.
796 // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
798 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
799 xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
801 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
802 xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
805 // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
807 // With respect to XHTML, paragraphs are still allowed here.
808 if (runparams.docbook_consider_allow_multi_par && !allowMultiPar())
809 runparams.docbook_make_pars = false;
811 runparams.pass_thru = true;
813 // - Write the main content of the inset.
814 xs.startDivision(false);
815 docbookParagraphs(text_, buffer(), xs, runparams);
818 // - Think about the arguments after the paragraph.
819 for (auto const & arg : appendedArguments)
820 arg->docbook(xs, np);
822 // - Close the required tags.
824 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
825 xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
827 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
828 xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
830 if (!il.docbookinnertag().empty() && il.docbookinnertag() != "NONE" && il.docbookinnertag() != "IGNORE")
831 xml::closeTag(xs, il.docbookinnertag(), il.docbookinnertagtype());
833 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
834 xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
836 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
837 xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
842 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
844 return insetAsXHTML(xs, runparams, WriteEverything);
849 // There are cases where we may need to close open fonts and such
850 // and then re-open them when we are done. This would be the case, e.g.,
851 // if we were otherwise about to write:
852 // <em>word <div class='foot'>footnote text.</div> emph</em>
853 // The problem isn't so much that the footnote text will get emphasized:
854 // we can handle that with CSS. The problem is that this is invalid XHTML.
855 // One solution would be to make the footnote <span>, but the problem is
856 // completely general, and so we'd have to make absolutely everything into
857 // span. What I think will work is to check if we're about to write "div" and,
858 // if so, try to close fonts, etc.
859 // There are probably limits to how well we can do here, though, and we will
860 // have to rely upon users not putting footnotes inside noun-type insets.
861 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
862 XHTMLOptions opts) const
864 // we will always want to output all our paragraphs when we are
866 OutputParams runparams = rp;
867 runparams.par_begin = 0;
868 runparams.par_end = text().paragraphs().size();
871 xs.startDivision(false);
872 xhtmlParagraphs(text_, buffer(), xs, runparams);
877 InsetLayout const & il = getLayout();
878 if (opts & WriteOuterTag)
879 xs << xml::StartTag(il.htmltag(), il.htmlattr());
881 if ((opts & WriteLabel) && !il.counter().empty()) {
882 BufferParams const & bp = buffer().masterBuffer()->params();
883 Counters & cntrs = bp.documentClass().counters();
884 cntrs.step(il.counter(), OutputUpdate);
885 // FIXME: translate to paragraph language
886 if (!il.htmllabel().empty()) {
887 docstring const lbl =
888 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
889 // FIXME is this check necessary?
891 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
893 xs << xml::EndTag(il.htmllabeltag());
898 if (opts & WriteInnerTag)
899 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
901 // we will eventually lose information about the containing inset
902 if (!allowMultiPar() || opts == JustText)
903 runparams.html_make_pars = false;
905 runparams.pass_thru = true;
907 xs.startDivision(false);
908 xhtmlParagraphs(text_, buffer(), xs, runparams);
911 if (opts & WriteInnerTag)
912 xs << xml::EndTag(il.htmlinnertag());
914 if (opts & WriteOuterTag)
915 xs << xml::EndTag(il.htmltag());
921 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
922 bool const post) const
924 OutputParams runparams = runparams_in;
925 runparams.local_font =
926 ¶graphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
928 runparams.pass_thru = true;
930 latexArgInsetsForParent(paragraphs(), os, runparams,
931 getLayout().postcommandargs(), "post:");
933 latexArgInsetsForParent(paragraphs(), os, runparams,
934 getLayout().latexargs());
938 void InsetText::cursorPos(BufferView const & bv,
939 CursorSlice const & sl, bool boundary, int & x, int & y) const
941 x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
942 y = bv.textMetrics(&text_).cursorY(sl, boundary);
946 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
949 Paragraph & first = paragraphs().front();
950 for (unsigned int i = 0; i < data.length(); ++i)
951 first.insertChar(i, data[i], font, trackChanges);
955 void InsetText::setDrawFrame(bool flag)
961 ColorCode InsetText::frameColor() const
967 void InsetText::setFrameColor(ColorCode col)
973 void InsetText::appendParagraphs(ParagraphList & plist)
975 // There is little we can do here to keep track of changes.
976 // As of 2006/10/20, appendParagraphs is used exclusively by
977 // LyXTabular::setMultiColumn. In this context, the paragraph break
978 // is lost irreversibly and the appended text doesn't really change
980 ParagraphList & pl = paragraphs();
982 ParagraphList::iterator pit = plist.begin();
983 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
985 mergeParagraph(buffer().params(), pl,
986 distance(pl.begin(), ins) - 1);
988 ParagraphList::iterator const pend = plist.end();
989 for (; pit != pend; ++pit)
994 void InsetText::addPreview(DocIterator const & text_inset_pos,
995 graphics::PreviewLoader & loader) const
997 ParagraphList::const_iterator pit = paragraphs().begin();
998 ParagraphList::const_iterator pend = paragraphs().end();
1001 DocIterator inset_pos = text_inset_pos;
1002 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
1004 for (; pit != pend; ++pit, ++pidx) {
1005 InsetList::const_iterator it = pit->insetList().begin();
1006 InsetList::const_iterator end = pit->insetList().end();
1007 inset_pos.pit() = pidx;
1008 for (; it != end; ++it) {
1009 inset_pos.pos() = it->pos;
1010 it->inset->addPreview(inset_pos, loader);
1016 ParagraphList const & InsetText::paragraphs() const
1018 return text_.paragraphs();
1022 ParagraphList & InsetText::paragraphs()
1024 return text_.paragraphs();
1028 bool InsetText::hasCProtectContent(bool fragile) const
1030 fragile |= getLayout().isNeedProtect();
1031 ParagraphList const & pars = paragraphs();
1032 pit_type pend = pit_type(paragraphs().size());
1033 for (pit_type pit = 0; pit != pend; ++pit) {
1034 Paragraph const & par = pars[size_type(pit)];
1035 if (par.needsCProtection(fragile))
1042 bool InsetText::insetAllowed(InsetCode code) const
1045 // Arguments, (plain) quotes and counter insets
1046 // are also allowed in PassThru insets
1052 return !isPassThru();
1057 bool InsetText::allowSpellCheck() const
1059 return getLayout().spellcheck() && !getLayout().isPassThru();
1063 bool InsetText::allowMultiPar() const
1065 return getLayout().isMultiPar();
1069 bool InsetText::forcePlainLayout(idx_type) const
1071 return getLayout().forcePlainLayout();
1075 bool InsetText::allowParagraphCustomization(idx_type) const
1077 return getLayout().allowParagraphCustomization();
1081 bool InsetText::forceLocalFontSwitch() const
1083 return getLayout().forceLocalFontSwitch();
1087 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1089 ParIterator it2 = it;
1091 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
1092 if (producesOutput()) {
1093 InsetLayout const & il = getLayout();
1094 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
1095 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
1097 // LYXERR0("Entering " << name());
1098 cnt.clearLastLayout();
1099 // FIXME cnt.saveLastCounter()?
1101 buffer().updateBuffer(it2, utype, deleted);
1103 // LYXERR0("Exiting " << name());
1104 cnt.restoreLastLayout();
1105 // FIXME cnt.restoreLastCounter()?
1107 // Record if this inset is embedded in a title layout
1108 // This is needed to decide when \maketitle is output.
1109 intitle_context_ = it.paragraph().layout().intitle;
1110 // Also check embedding layouts
1111 size_t const n = it.depth();
1112 for (size_t i = 0; i < n; ++i) {
1113 if (it[i].paragraph().layout().intitle) {
1114 intitle_context_ = true;
1119 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1120 // Note that we do not need to call:
1121 // tclass.counters().clearLastLayout()
1122 // since we are saving and restoring the existing counters, etc.
1123 Counters savecnt = tclass.counters();
1124 tclass.counters().reset();
1125 // we need float information even in note insets (#9760)
1126 tclass.counters().current_float(savecnt.current_float());
1127 tclass.counters().isSubfloat(savecnt.isSubfloat());
1128 buffer().updateBuffer(it2, utype, deleted);
1129 tclass.counters() = move(savecnt);
1134 void InsetText::toString(odocstream & os) const
1136 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1140 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1141 bool const shorten) const
1143 if (!getLayout().isInToc())
1145 text().forOutliner(os, maxlen, shorten);
1149 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1150 UpdateType utype, TocBackend & backend) const
1152 DocIterator dit = cdit;
1153 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1154 iterateForToc(dit, output_active, utype, backend);
1158 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1159 UpdateType utype, TocBackend & backend) const
1161 DocIterator dit = cdit;
1162 // This also ensures that any document has a table of contents
1163 shared_ptr<Toc> toc = backend.toc("tableofcontents");
1165 BufferParams const & bufparams = buffer_->params();
1166 int const min_toclevel = bufparams.documentClass().min_toclevel();
1167 // we really should have done this before we got here, but it
1168 // can't hurt too much to do it again
1169 bool const doing_output = output_active && producesOutput();
1171 // For each paragraph,
1172 // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1173 // paragraphs as needed.
1174 // * Traverse its insets and let them add their toc items
1175 // * Compute the main table of contents (this is hardcoded)
1176 // * Add the list of changes
1177 ParagraphList const & pars = paragraphs();
1178 pit_type pend = paragraphs().size();
1179 // Record pairs {start,end} of where a toc item was opened for a paragraph
1180 // and where it must be closed
1181 stack<pair<pit_type, pit_type>> addtotoc_stack;
1183 for (pit_type pit = 0; pit != pend; ++pit) {
1184 Paragraph const & par = pars[pit];
1188 // Custom AddToToc in paragraph layouts (i.e. theorems)
1189 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1191 openAddToTocForParagraph(pit, dit, output_active, backend);
1192 addtotoc_stack.push({pit, end});
1195 // If we find an InsetArgument that is supposed to provide the TOC caption,
1196 // we'll save it for use later.
1197 InsetArgument const * arginset = nullptr;
1198 for (auto const & table : par.insetList()) {
1199 dit.pos() = table.pos;
1200 table.inset->addToToc(dit, doing_output, utype, backend);
1201 if (InsetArgument const * x = table.inset->asInsetArgument())
1202 if (x->isTocCaption())
1206 // End custom AddToToc in paragraph layouts
1207 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1208 // execute the closing function
1209 closeAddToTocForParagraph(addtotoc_stack.top().first,
1210 addtotoc_stack.top().second, backend);
1211 addtotoc_stack.pop();
1214 // now the toc entry for the paragraph in the main table of contents
1215 int const toclevel = text().getTocLevel(pit);
1216 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1217 // insert this into the table of contents
1218 docstring tocstring;
1219 int const length = (doing_output && utype == OutputUpdate) ?
1220 INT_MAX : TOC_ENTRY_LENGTH;
1222 tocstring = par.labelString();
1223 if (!tocstring.empty())
1225 arginset->text().forOutliner(tocstring, length);
1227 par.forOutliner(tocstring, length);
1229 toc->push_back(TocItem(dit, toclevel - min_toclevel,
1230 tocstring, doing_output));
1233 // And now the list of changes.
1234 par.addChangesToToc(dit, buffer(), doing_output, backend);
1239 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1240 DocIterator const & dit,
1242 TocBackend & backend) const
1244 Paragraph const & par = paragraphs()[pit];
1245 TocBuilder & b = backend.builder(par.layout().tocType());
1246 docstring const & label = par.labelString();
1247 b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1248 return text().lastInSequence(pit);
1252 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1253 TocBackend & backend) const
1255 Paragraph const & par = paragraphs()[start];
1256 TocBuilder & b = backend.builder(par.layout().tocType());
1257 if (par.layout().isTocCaption()) {
1259 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1260 b.argumentItem(str);
1266 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1268 if (buffer().isClean())
1269 return Inset::notifyCursorLeaves(old, cur);
1271 // find text inset in old cursor
1272 Cursor insetCur = old;
1273 int scriptSlice = insetCur.find(this);
1274 // we can try to continue here. returning true means
1275 // the cursor is "now" invalid. which it was.
1276 LASSERT(scriptSlice != -1, return true);
1277 insetCur.cutOff(scriptSlice);
1278 LASSERT(&insetCur.inset() == this, return true);
1280 // update the old paragraph's words
1281 insetCur.paragraph().updateWords();
1283 return Inset::notifyCursorLeaves(old, cur);
1287 bool InsetText::completionSupported(Cursor const & cur) const
1289 //LASSERT(&cur.bv().cursor().inset() == this, return false);
1290 return text_.completionSupported(cur);
1294 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1296 return completionSupported(cur);
1300 bool InsetText::automaticInlineCompletion() const
1302 return lyxrc.completion_inline_text;
1306 bool InsetText::automaticPopupCompletion() const
1308 return lyxrc.completion_popup_text;
1312 bool InsetText::showCompletionCursor() const
1314 return lyxrc.completion_cursor_text &&
1315 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1319 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1321 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1325 docstring InsetText::completionPrefix(Cursor const & cur) const
1327 if (!completionSupported(cur))
1329 return text_.completionPrefix(cur);
1333 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1336 if (!completionSupported(cur))
1339 return text_.insertCompletion(cur, s, finished);
1343 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1344 Dimension & dim) const
1346 TextMetrics const & tm = cur.bv().textMetrics(&text_);
1347 tm.completionPosAndDim(cur, x, y, dim);
1351 string InsetText::contextMenu(BufferView const &, int, int) const
1353 string context_menu = contextMenuName();
1354 if (context_menu != InsetText::contextMenuName())
1355 context_menu += ";" + InsetText::contextMenuName();
1356 return context_menu;
1360 string InsetText::contextMenuName() const
1362 return "context-edit";
1366 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1368 OutputParams rp(&buffer().params().encoding());
1369 rp.for_tooltip = true;
1370 odocstringstream oss;
1373 ParagraphList::const_iterator beg = paragraphs().begin();
1374 ParagraphList::const_iterator end = paragraphs().end();
1375 ParagraphList::const_iterator it = beg;
1376 bool ref_printed = false;
1378 for (; it != end; ++it) {
1381 if ((*it).isRTL(buffer().params()))
1382 oss << "<div dir=\"rtl\">";
1383 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1384 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1387 docstring str = oss.str();
1389 str += from_ascii("\n\n") + _("[contains tracked changes]");
1390 support::truncateWithEllipsis(str, len);
1395 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1397 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1401 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1403 // Nested cprotect content needs \cprotect
1405 if (producesOutput() && hasCProtectContent(fragile))
1408 // Environments generally need cprotection in fragile context
1409 if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1412 if (!getLayout().needsCProtect())
1415 // Environments and "no latex" types (e.g., knitr chunks)
1416 // need cprotection regardless the content
1417 if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1420 // If the inset does not produce output (e.g. Note or Branch),
1421 // we can ignore the contained paragraphs
1422 if (!producesOutput())
1425 // Commands need cprotection if they contain specific chars
1426 int const nchars_escape = 9;
1427 static char_type const chars_escape[nchars_escape] = {
1428 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1430 ParagraphList const & pars = paragraphs();
1431 pit_type pend = pit_type(paragraphs().size());
1433 for (pit_type pit = 0; pit != pend; ++pit) {
1434 Paragraph const & par = pars[size_type(pit)];
1435 if (par.needsCProtection(fragile))
1437 docstring const par_str = par.asString();
1438 for (int k = 0; k < nchars_escape; k++) {
1439 if (contains(par_str, chars_escape[k]))