]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
819c87d6a6bef5511f1ed8693e22719b85abd532
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetLayout.h"
14 #include "InsetText.h"
15
16 #include "insets/InsetArgument.h"
17 #include "insets/InsetLayout.h"
18
19 #include "buffer_funcs.h"
20 #include "Buffer.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "CompletionList.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "InsetList.h"
32 #include "Intl.h"
33 #include "Language.h"
34 #include "Layout.h"
35 #include "LaTeXFeatures.h"
36 #include "Lexer.h"
37 #include "lyxfind.h"
38 #include "LyXRC.h"
39 #include "MetricsInfo.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_plaintext.h"
43 #include "output_xhtml.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TexRow.h"
48 #include "texstream.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53 #include "TocBuilder.h"
54
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
57
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/Changer.h"
64
65 #include <algorithm>
66 #include <stack>
67
68
69 using namespace std;
70 using namespace lyx::support;
71
72
73 namespace lyx {
74
75 using graphics::PreviewLoader;
76
77
78 /////////////////////////////////////////////////////////////////////
79
80 InsetText::InsetText(Buffer * buf, UsePlain type)
81         : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
82           frame_color_(Color_insetframe),
83         text_(this, type == DefaultLayout)
84 {
85 }
86
87
88 InsetText::InsetText(InsetText const & in)
89         : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
90           intitle_context_(false), frame_color_(in.frame_color_),
91           text_(this, in.text_)
92 {
93 }
94
95
96 void InsetText::setBuffer(Buffer & buf)
97 {
98         ParagraphList::iterator end = paragraphs().end();
99         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100                 it->setInsetBuffers(buf);
101         Inset::setBuffer(buf);
102 }
103
104
105 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
106 {
107         text_.setMacrocontextPosition(pos);
108
109         ParagraphList::const_iterator pit = paragraphs().begin();
110         ParagraphList::const_iterator pend = paragraphs().end();
111         for (; pit != pend; ++pit) {
112                 InsetList::const_iterator iit = pit->insetList().begin();
113                 InsetList::const_iterator end = pit->insetList().end();
114                 for (; iit != end; ++iit) {
115                         if (InsetText * txt = iit->inset->asInsetText()) {
116                                 DocIterator ppos(pos);
117                                 ppos.push_back(CursorSlice(*txt));
118                                 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
119                         }
120                 }
121         }
122 }
123
124
125 void InsetText::clear()
126 {
127         ParagraphList & pars = paragraphs();
128         LBUFERR(!pars.empty());
129
130         // This is a gross hack...
131         Layout const & old_layout = pars.begin()->layout();
132
133         pars.clear();
134         pars.push_back(Paragraph());
135         pars.begin()->setInsetOwner(this);
136         pars.begin()->setLayout(old_layout);
137 }
138
139
140 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
141 {
142         TextMetrics const & tm = bv.textMetrics(&text_);
143         Dimension dim = tm.dim();
144         dim.wid += leftOffset(&bv) + rightOffset(&bv);
145         dim.des += bottomOffset(&bv);
146         dim.asc += topOffset(&bv);
147         return dim;
148 }
149
150
151 void InsetText::write(ostream & os) const
152 {
153         os << "Text\n";
154         text_.write(os);
155 }
156
157
158 void InsetText::read(Lexer & lex)
159 {
160         clear();
161
162         // delete the initial paragraph
163         Paragraph oldpar = *paragraphs().begin();
164         paragraphs().clear();
165         ErrorList errorList;
166         lex.setContext("InsetText::read");
167         bool res = text_.read(lex, errorList, this);
168
169         if (!res)
170                 lex.printError("Missing \\end_inset at this point. ");
171
172         // sanity check
173         // ensure we have at least one paragraph.
174         if (paragraphs().empty())
175                 paragraphs().push_back(oldpar);
176         // Force default font, if so requested
177         // This avoids paragraphs in buffer language that would have a
178         // foreign language after a document language change, and it ensures
179         // that all new text in ERT and similar gets the "latex" language,
180         // since new text inherits the language from the last position of the
181         // existing text.  As a side effect this makes us also robust against
182         // bugs in LyX that might lead to font changes in ERT in .lyx files.
183         fixParagraphsFont();
184 }
185
186
187 void InsetText::setOuterFont(BufferView & bv, FontInfo const & outer) const
188 {
189         TextMetrics & tm = bv.textMetrics(&text_);
190         FontInfo tmpfont = getFont();
191         tmpfont.realize(outer);
192         tm.font_.fontInfo() = tmpfont;
193 }
194
195
196 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
197 {
198         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
199
200         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
201
202         int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
203         mi.base.textwidth -= horiz_offset;
204
205         // Remember the full outer font
206         setOuterFont(*mi.base.bv, mi.base.font);
207         // and use it in these metrics computation.
208         mi.base.font = tm.font_.fontInfo();
209
210         // This can happen when a layout has a left and right margin,
211         // and the view is made very narrow. We can't do better than
212         // to draw it partly out of view (bug 5890).
213         if (mi.base.textwidth < 1)
214                 mi.base.textwidth = 1;
215
216         if (hasFixedWidth())
217                 tm.metrics(mi, dim, mi.base.textwidth);
218         else
219                 tm.metrics(mi, dim);
220         mi.base.textwidth += horiz_offset;
221         dim.asc += topOffset(mi.base.bv);
222         dim.des += bottomOffset(mi.base.bv);
223         dim.wid += horiz_offset;
224 }
225
226
227 void InsetText::draw(PainterInfo & pi, int x, int y) const
228 {
229         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
230
231         int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
232         int const w = tm.width() + (horiz_offset - horiz_offset / 2);
233         int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
234         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
235         int const xframe = x + leftOffset(pi.base.bv) / 2;
236         bool change_drawn = false;
237         if (pi.full_repaint)
238                         pi.pain.fillRectangle(xframe, yframe, w, h,
239                                 pi.backgroundColor(this));
240
241         {
242                 Changer dummy = changeVar(pi.background_color,
243                                             pi.backgroundColor(this, false));
244                 // The change tracking cue must not be inherited
245                 Changer dummy2 = changeVar(pi.change, Change());
246                 tm.draw(pi, x + leftOffset(pi.base.bv), y);
247         }
248
249         if (drawFrame_) {
250                 // Change color of the frame in tracked changes, like for tabulars.
251                 // Only do so if the color is not custom. But do so even if RowPainter
252                 // handles the strike-through already.
253                 Color c;
254                 if (pi.change.changed()
255                     // Originally, these are the colors with role Text, from role() in
256                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
257                     // types, and also maybe it need not match in the future.
258                     && (frameColor() == Color_foreground
259                         || frameColor() == Color_cursor
260                         || frameColor() == Color_preview
261                         || frameColor() == Color_tabularline
262                         || frameColor() == Color_previewframe)) {
263                         c = pi.change.color();
264                         change_drawn = true;
265                 } else
266                         c = frameColor();
267                 pi.pain.rectangle(xframe, yframe, w, h, c);
268         }
269
270         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
271                 // Do not draw the change tracking cue if already done by RowPainter and
272                 // do not draw the cue for INSERTED if the information is already in the
273                 // color of the frame
274                 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
275 }
276
277
278 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
279 {
280         pit_type const pit = front ? 0 : paragraphs().size() - 1;
281         pos_type pos = front ? 0 : paragraphs().back().size();
282
283         // if visual information is not to be ignored, move to extreme right/left
284         if (entry_from != ENTRY_DIRECTION_IGNORE) {
285                 Cursor temp_cur = cur;
286                 temp_cur.pit() = pit;
287                 temp_cur.pos() = pos;
288                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
289                 pos = temp_cur.pos();
290         }
291
292         cur.top().setPitPos(pit, pos);
293         cur.setCurrentFont();
294         cur.finishUndo();
295 }
296
297
298 Inset * InsetText::editXY(Cursor & cur, int x, int y)
299 {
300         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
301 }
302
303
304 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
305 {
306         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
307
308 #if 0
309         // See bug #9042, for instance.
310         if (isPassThru()) {
311                 // Force any new text to latex_language FIXME: This
312                 // should only be necessary in constructor, but new
313                 // paragraphs that are created by pressing enter at
314                 // the start of an existing paragraph get the buffer
315                 // language and not latex_language, so we take this
316                 // brute force approach.
317                 cur.current_font.setLanguage(latex_language);
318                 cur.real_current_font.setLanguage(latex_language);
319         }
320 #endif
321
322         switch (cmd.action()) {
323         case LFUN_PASTE:
324         case LFUN_CLIPBOARD_PASTE:
325         case LFUN_SELECTION_PASTE:
326         case LFUN_PRIMARY_SELECTION_PASTE:
327                 text_.dispatch(cur, cmd);
328                 // If we we can only store plain text, we must reset all
329                 // attributes.
330                 // FIXME: Change only the pasted paragraphs
331                 fixParagraphsFont();
332                 break;
333
334         case LFUN_INSET_SPLIT:
335         case LFUN_INSET_DISSOLVE: {
336                 bool const main_inset = text_.isMainText();
337                 bool const target_inset = cmd.argument().empty()
338                         || cmd.getArg(0) == insetName(lyxCode());
339
340                 if (!main_inset && target_inset) {
341                         UndoGroupHelper ugh(&buffer());
342                         // Text::dissolveInset assumes that the cursor
343                         // is inside the Inset.
344                         if (&cur.inset() != this) {
345                                 cur.recordUndo();
346                                 cur.pushBackward(*this);
347                         }
348                         text_.dispatch(cur, cmd);
349                 } else
350                         cur.undispatched();
351                 break;
352         }
353
354         default:
355                 text_.dispatch(cur, cmd);
356         }
357
358         if (!cur.result().dispatched())
359                 Inset::doDispatch(cur, cmd);
360 }
361
362
363 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
364         FuncStatus & status) const
365 {
366         switch (cmd.action()) {
367         case LFUN_INSET_SPLIT:
368         case LFUN_INSET_DISSOLVE: {
369                 bool const main_inset = text_.isMainText();
370                 bool const target_inset = cmd.argument().empty()
371                         || cmd.getArg(0) == insetName(lyxCode());
372
373                 if (target_inset)
374                         status.setEnabled(!main_inset);
375                 return target_inset;
376         }
377
378         case LFUN_ARGUMENT_INSERT: {
379                 string const arg = cmd.getArg(0);
380                 if (arg.empty()) {
381                         status.setEnabled(false);
382                         return true;
383                 }
384                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
385                         return text_.getStatus(cur, cmd, status);
386
387                 Layout::LaTeXArgMap args = getLayout().args();
388                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
389                 if (lait != args.end()) {
390                         status.setEnabled(true);
391                         for (Paragraph const & par : paragraphs())
392                                 for (auto const & table : par.insetList())
393                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
394                                                 if (ins->name() == arg) {
395                                                         // we have this already
396                                                         status.setEnabled(false);
397                                                         return true;
398                                                 }
399                 } else
400                         status.setEnabled(false);
401                 return true;
402         }
403
404         default:
405                 // Dispatch only to text_ if the cursor is inside
406                 // the text_. It is not for context menus (bug 5797).
407                 bool ret = false;
408                 if (cur.text() == &text_)
409                         ret = text_.getStatus(cur, cmd, status);
410
411                 if (!ret)
412                         ret = Inset::getStatus(cur, cmd, status);
413                 return ret;
414         }
415 }
416
417
418 void InsetText::fixParagraphsFont()
419 {
420         Font font(inherit_font, buffer().params().language);
421         font.setLanguage(latex_language);
422         ParagraphList::iterator par = paragraphs().begin();
423         ParagraphList::iterator const end = paragraphs().end();
424         while (par != end) {
425                 if (par->isPassThru())
426                         par->resetFonts(font);
427                 if (!par->allowParagraphCustomization())
428                         par->params().clear();
429                 ++par;
430         }
431 }
432
433
434 // bool InsetText::isChanged() const
435 // {
436 //      ParagraphList::const_iterator pit = paragraphs().begin();
437 //      ParagraphList::const_iterator end = paragraphs().end();
438 //      for (; pit != end; ++pit) {
439 //              if (pit->isChanged())
440 //                      return true;
441 //      }
442 //      return false;
443 // }
444
445
446 void InsetText::setChange(Change const & change)
447 {
448         ParagraphList::iterator pit = paragraphs().begin();
449         ParagraphList::iterator end = paragraphs().end();
450         for (; pit != end; ++pit) {
451                 pit->setChange(change);
452         }
453 }
454
455
456 void InsetText::acceptChanges()
457 {
458         text_.acceptChanges();
459 }
460
461
462 void InsetText::rejectChanges()
463 {
464         text_.rejectChanges();
465 }
466
467
468 void InsetText::validate(LaTeXFeatures & features) const
469 {
470         features.useInsetLayout(getLayout());
471         for (Paragraph const & p : paragraphs())
472                 p.validate(features);
473 }
474
475
476 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
477 {
478         // This implements the standard way of handling the LaTeX
479         // output of a text inset, either a command or an
480         // environment. Standard collapsible insets should not
481         // redefine this, non-standard ones may call this.
482         InsetLayout const & il = getLayout();
483         if (il.forceOwnlines())
484                 os << breakln;
485         bool needendgroup = false;
486         if (!il.latexname().empty()) {
487                 if (il.latextype() == InsetLaTeXType::COMMAND) {
488                         // FIXME UNICODE
489                         // FIXME \protect should only be used for fragile
490                         //    commands, but we do not provide this information yet.
491                         if (hasCProtectContent(runparams.moving_arg)) {
492                                 if (contains(runparams.active_chars, '^')) {
493                                         // cprotect relies on ^ being on catcode 7
494                                         os << "\\begingroup\\catcode`\\^=7";
495                                         needendgroup = true;
496                                 }
497                                 os << "\\cprotect";
498                         } else if (runparams.moving_arg)
499                                 os << "\\protect";
500                         os << '\\' << from_utf8(il.latexname());
501                         if (!il.latexargs().empty())
502                                 getArgs(os, runparams);
503                         if (!il.latexparam().empty())
504                                 os << from_utf8(il.latexparam());
505                         os << '{';
506                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
507                         if (il.isDisplay())
508                                 os << breakln;
509                         else
510                                 os << safebreakln;
511                         if (runparams.lastid != -1)
512                                 os.texrow().start(runparams.lastid,
513                                                   runparams.lastpos);
514                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
515                         if (!il.latexargs().empty())
516                                 getArgs(os, runparams);
517                         if (!il.latexparam().empty())
518                                 os << from_utf8(il.latexparam());
519                         os << '\n';
520                 }
521         } else {
522                 if (!il.latexargs().empty())
523                         getArgs(os, runparams);
524                 if (!il.latexparam().empty())
525                         os << from_utf8(il.latexparam());
526         }
527
528         if (!il.leftdelim().empty())
529                 os << il.leftdelim();
530
531         OutputParams rp = runparams;
532         if (isPassThru())
533                 rp.pass_thru = true;
534         if (il.isNeedProtect())
535                 rp.moving_arg = true;
536         if (il.isNeedMBoxProtect())
537                 ++rp.inulemcmd;
538         if (!il.passThruChars().empty())
539                 rp.pass_thru_chars += il.passThruChars();
540         if (!il.newlineCmd().empty())
541                 rp.newlinecmd = il.newlineCmd();
542         rp.par_begin = 0;
543         rp.par_end = paragraphs().size();
544
545         // Output the contents of the inset
546         latexParagraphs(buffer(), text_, os, rp);
547         runparams.encoding = rp.encoding;
548         // Pass the post_macros upstream
549         runparams.post_macro = rp.post_macro;
550         // These need to be passed upstream as well
551         runparams.need_maketitle = rp.need_maketitle;
552         runparams.have_maketitle = rp.have_maketitle;
553
554         if (!il.rightdelim().empty())
555                 os << il.rightdelim();
556
557         if (!il.latexname().empty()) {
558                 if (il.latextype() == InsetLaTeXType::COMMAND) {
559                         os << "}";
560                         if (!il.postcommandargs().empty())
561                                 getArgs(os, runparams, true);
562                         if (needendgroup)
563                                 os << "\\endgroup";
564                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
565                         // A comment environment doesn't need a % before \n\end
566                         if (il.isDisplay() || runparams.inComment)
567                                 os << breakln;
568                         else
569                                 os << safebreakln;
570                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
571                         if (!il.isDisplay())
572                                 os.protectSpace(true);
573                 }
574         }
575         if (il.forceOwnlines())
576                 os << breakln;
577 }
578
579
580 int InsetText::plaintext(odocstringstream & os,
581         OutputParams const & runparams, size_t max_length) const
582 {
583         ParagraphList::const_iterator beg = paragraphs().begin();
584         ParagraphList::const_iterator end = paragraphs().end();
585         ParagraphList::const_iterator it = beg;
586         bool ref_printed = false;
587         int len = 0;
588         for (; it != end; ++it) {
589                 if (it != beg) {
590                         os << '\n';
591                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
592                                 os << '\n';
593                 }
594                 odocstringstream oss;
595                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
596                 docstring const str = oss.str();
597                 os << str;
598                 // FIXME: len is not computed fully correctly; in principle,
599                 // we have to count the characters after the last '\n'
600                 len = str.size();
601                 if (os.str().size() >= max_length)
602                         break;
603         }
604
605         return len;
606 }
607
608
609
610 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
611 {
612         docbook(xs, rp, WriteEverything);
613 }
614
615
616 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
617 {
618         // we will always want to output all our paragraphs when we are
619         // called this way.
620         OutputParams runparams = rp;
621         runparams.par_begin = 0;
622         runparams.par_end = text().paragraphs().size();
623
624         if (undefined()) {
625                 xs.startDivision(false);
626                 docbookParagraphs(text_, buffer(), xs, runparams);
627                 xs.endDivision();
628                 return;
629         }
630
631         InsetLayout const & il = getLayout();
632
633         // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
634         // else, typically outside the current paragraph).
635         if (!rp.docbook_generate_info && il.docbookininfo() != "never")
636                 return;
637
638         // In some cases, the input parameters must be overridden for outer tags.
639         bool writeOuterTag = opts & WriteOuterTag;
640         if (writeOuterTag) {
641                 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
642                 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
643                         auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
644                         auto parSize = (size_t) par.size();
645                         return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
646                 });
647                 writeOuterTag = !allBibitems;
648         }
649
650         // Detect arguments that should be output before/after the paragraph.
651         // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
652         // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
653         std::set<InsetArgument const *> prependedArguments;
654         for (auto const & par : paragraphs()) {
655                 for (pos_type i = 0; i < par.size(); ++i) {
656                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
657                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
658                                 if (arg->docbookargumentbeforemaintag())
659                                         prependedArguments.insert(par.getInset(i)->asInsetArgument());
660                         }
661                 }
662         }
663
664         std::set<InsetArgument const *> appendedArguments;
665         for (auto const & par : paragraphs()) {
666                 for (pos_type i = 0; i < par.size(); ++i) {
667                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
668                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
669                                 if (arg->docbookargumentaftermaintag())
670                     appendedArguments.insert(par.getInset(i)->asInsetArgument());
671                         }
672                 }
673         }
674
675         // Start outputting this inset.
676         // - First, wrapper around the inset and its main tag.
677         if (writeOuterTag) {
678                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
679                         xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
680
681                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
682                         docstring attrs = docstring();
683                         if (!il.docbookattr().empty())
684                                 attrs += from_ascii(il.docbookattr());
685                         if (il.docbooktag() == "link")
686                                 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
687                         xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
688                 }
689         }
690
691         // - Think about the arguments before the paragraph.
692         OutputParams np = runparams;
693         np.docbook_in_par = true;
694         for (auto const & arg : prependedArguments)
695                 arg->docbook(xs, np);
696
697         // - Mark the newly generated arguments are not-to-be-generated-again. Do the same for arguments that will follow.
698         runparams.docbook_prepended_arguments = std::move(prependedArguments);
699         runparams.docbook_appended_arguments = appendedArguments;
700
701         // - Deal with the first item.
702         // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
703         if (writeOuterTag) {
704                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
705                         xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
706
707                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
708                         xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
709         }
710
711         // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
712
713         // With respect to XHTML, paragraphs are still allowed here.
714         if (!allowMultiPar())
715                 runparams.docbook_make_pars = false;
716         if (il.isPassThru())
717                 runparams.pass_thru = true;
718
719         // - Write the main content of the inset.
720         xs.startDivision(false);
721         docbookParagraphs(text_, buffer(), xs, runparams);
722         xs.endDivision();
723
724         // - Think about the arguments after the paragraph.
725         for (auto const & arg : appendedArguments)
726                 arg->docbook(xs, np);
727
728         // - Close the required tags.
729         if (writeOuterTag) {
730                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
731                         xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
732
733                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
734                         xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
735
736                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
737                         xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
738
739                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
740                         xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
741         }
742 }
743
744
745 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
746 {
747         return insetAsXHTML(xs, runparams, WriteEverything);
748 }
749
750
751 // FIXME XHTML
752 // There are cases where we may need to close open fonts and such
753 // and then re-open them when we are done. This would be the case, e.g.,
754 // if we were otherwise about to write:
755 //              <em>word <div class='foot'>footnote text.</div> emph</em>
756 // The problem isn't so much that the footnote text will get emphasized:
757 // we can handle that with CSS. The problem is that this is invalid XHTML.
758 // One solution would be to make the footnote <span>, but the problem is
759 // completely general, and so we'd have to make absolutely everything into
760 // span. What I think will work is to check if we're about to write "div" and,
761 // if so, try to close fonts, etc.
762 // There are probably limits to how well we can do here, though, and we will
763 // have to rely upon users not putting footnotes inside noun-type insets.
764 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
765                                   XHTMLOptions opts) const
766 {
767         // we will always want to output all our paragraphs when we are
768         // called this way.
769         OutputParams runparams = rp;
770         runparams.par_begin = 0;
771         runparams.par_end = text().paragraphs().size();
772
773         if (undefined()) {
774                 xs.startDivision(false);
775                 xhtmlParagraphs(text_, buffer(), xs, runparams);
776                 xs.endDivision();
777                 return docstring();
778         }
779
780         InsetLayout const & il = getLayout();
781         if (opts & WriteOuterTag)
782                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
783
784         if ((opts & WriteLabel) && !il.counter().empty()) {
785                 BufferParams const & bp = buffer().masterBuffer()->params();
786                 Counters & cntrs = bp.documentClass().counters();
787                 cntrs.step(il.counter(), OutputUpdate);
788                 // FIXME: translate to paragraph language
789                 if (!il.htmllabel().empty()) {
790                         docstring const lbl =
791                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
792                         // FIXME is this check necessary?
793                         if (!lbl.empty()) {
794                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
795                                 xs << lbl;
796                                 xs << xml::EndTag(il.htmllabeltag());
797                         }
798                 }
799         }
800
801         if (opts & WriteInnerTag)
802                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
803
804         // we will eventually lose information about the containing inset
805         if (!allowMultiPar() || opts == JustText)
806                 runparams.html_make_pars = false;
807         if (il.isPassThru())
808                 runparams.pass_thru = true;
809
810         xs.startDivision(false);
811         xhtmlParagraphs(text_, buffer(), xs, runparams);
812         xs.endDivision();
813
814         if (opts & WriteInnerTag)
815                 xs << xml::EndTag(il.htmlinnertag());
816
817         if (opts & WriteOuterTag)
818                 xs << xml::EndTag(il.htmltag());
819
820         return docstring();
821 }
822
823
824 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
825                         bool const post) const
826 {
827         OutputParams runparams = runparams_in;
828         runparams.local_font =
829                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
830         if (isPassThru())
831                 runparams.pass_thru = true;
832         if (post)
833                 latexArgInsetsForParent(paragraphs(), os, runparams,
834                                         getLayout().postcommandargs(), "post:");
835         else
836                 latexArgInsetsForParent(paragraphs(), os, runparams,
837                                         getLayout().latexargs());
838 }
839
840
841 void InsetText::cursorPos(BufferView const & bv,
842                 CursorSlice const & sl, bool boundary, int & x, int & y) const
843 {
844         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
845         y = bv.textMetrics(&text_).cursorY(sl, boundary);
846 }
847
848
849 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
850 {
851         clear();
852         Paragraph & first = paragraphs().front();
853         for (unsigned int i = 0; i < data.length(); ++i)
854                 first.insertChar(i, data[i], font, trackChanges);
855 }
856
857
858 void InsetText::setDrawFrame(bool flag)
859 {
860         drawFrame_ = flag;
861 }
862
863
864 ColorCode InsetText::frameColor() const
865 {
866         return frame_color_;
867 }
868
869
870 void InsetText::setFrameColor(ColorCode col)
871 {
872         frame_color_ = col;
873 }
874
875
876 void InsetText::appendParagraphs(ParagraphList & plist)
877 {
878         // There is little we can do here to keep track of changes.
879         // As of 2006/10/20, appendParagraphs is used exclusively by
880         // LyXTabular::setMultiColumn. In this context, the paragraph break
881         // is lost irreversibly and the appended text doesn't really change
882
883         ParagraphList & pl = paragraphs();
884
885         ParagraphList::iterator pit = plist.begin();
886         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
887         ++pit;
888         mergeParagraph(buffer().params(), pl,
889                        distance(pl.begin(), ins) - 1);
890
891         ParagraphList::iterator const pend = plist.end();
892         for (; pit != pend; ++pit)
893                 pl.push_back(*pit);
894 }
895
896
897 void InsetText::addPreview(DocIterator const & text_inset_pos,
898         PreviewLoader & loader) const
899 {
900         ParagraphList::const_iterator pit = paragraphs().begin();
901         ParagraphList::const_iterator pend = paragraphs().end();
902         int pidx = 0;
903
904         DocIterator inset_pos = text_inset_pos;
905         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
906
907         for (; pit != pend; ++pit, ++pidx) {
908                 InsetList::const_iterator it  = pit->insetList().begin();
909                 InsetList::const_iterator end = pit->insetList().end();
910                 inset_pos.pit() = pidx;
911                 for (; it != end; ++it) {
912                         inset_pos.pos() = it->pos;
913                         it->inset->addPreview(inset_pos, loader);
914                 }
915         }
916 }
917
918
919 ParagraphList const & InsetText::paragraphs() const
920 {
921         return text_.paragraphs();
922 }
923
924
925 ParagraphList & InsetText::paragraphs()
926 {
927         return text_.paragraphs();
928 }
929
930
931 bool InsetText::hasCProtectContent(bool fragile) const
932 {
933         fragile |= getLayout().isNeedProtect();
934         ParagraphList const & pars = paragraphs();
935         pit_type pend = pit_type(paragraphs().size());
936         for (pit_type pit = 0; pit != pend; ++pit) {
937                 Paragraph const & par = pars[size_type(pit)];
938                 if (par.needsCProtection(fragile))
939                         return true;
940         }
941         return false;
942 }
943
944
945 bool InsetText::insetAllowed(InsetCode code) const
946 {
947         switch (code) {
948         // Arguments, (plain) quotes and counter insets 
949         // are also allowed in PassThru insets
950         case ARG_CODE:
951         case QUOTE_CODE:
952         case COUNTER_CODE:
953                 return true;
954         default:
955                 return !isPassThru();
956         }
957 }
958
959
960 bool InsetText::allowSpellCheck() const
961 {
962         return getLayout().spellcheck() && !getLayout().isPassThru();
963 }
964
965
966 bool InsetText::allowMultiPar() const
967 {
968         return getLayout().isMultiPar();
969 }
970
971
972 bool InsetText::forcePlainLayout(idx_type) const
973 {
974         return getLayout().forcePlainLayout();
975 }
976
977
978 bool InsetText::allowParagraphCustomization(idx_type) const
979 {
980         return getLayout().allowParagraphCustomization();
981 }
982
983
984 bool InsetText::forceLocalFontSwitch() const
985 {
986         return getLayout().forceLocalFontSwitch();
987 }
988
989
990 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
991 {
992         ParIterator it2 = it;
993         it2.forwardPos();
994         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
995         if (producesOutput()) {
996                 InsetLayout const & il = getLayout();
997                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
998                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
999                 if (save_layouts) {
1000                         // LYXERR0("Entering " << name());
1001                         cnt.clearLastLayout();
1002                         // FIXME cnt.saveLastCounter()?
1003                 }
1004                 buffer().updateBuffer(it2, utype, deleted);
1005                 if (save_layouts) {
1006                         // LYXERR0("Exiting " << name());
1007                         cnt.restoreLastLayout();
1008                         // FIXME cnt.restoreLastCounter()?
1009                 }
1010                 // Record if this inset is embedded in a title layout
1011                 // This is needed to decide when \maketitle is output.
1012                 intitle_context_ = it.paragraph().layout().intitle;
1013                 // Also check embedding layouts
1014                 size_t const n = it.depth();
1015                 for (size_t i = 0; i < n; ++i) {
1016                         if (it[i].paragraph().layout().intitle) {
1017                                 intitle_context_ = true;
1018                                 break;
1019                         }
1020                 }
1021         } else {
1022                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
1023                 // Note that we do not need to call:
1024                 //      tclass.counters().clearLastLayout()
1025                 // since we are saving and restoring the existing counters, etc.
1026                 Counters savecnt = tclass.counters();
1027                 tclass.counters().reset();
1028                 // we need float information even in note insets (#9760)
1029                 tclass.counters().current_float(savecnt.current_float());
1030                 tclass.counters().isSubfloat(savecnt.isSubfloat());
1031                 buffer().updateBuffer(it2, utype, deleted);
1032                 tclass.counters() = move(savecnt);
1033         }
1034 }
1035
1036
1037 void InsetText::toString(odocstream & os) const
1038 {
1039         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1040 }
1041
1042
1043 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1044                                                         bool const shorten) const
1045 {
1046         if (!getLayout().isInToc())
1047                 return;
1048         text().forOutliner(os, maxlen, shorten);
1049 }
1050
1051
1052 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1053                                                  UpdateType utype, TocBackend & backend) const
1054 {
1055         DocIterator dit = cdit;
1056         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1057         iterateForToc(dit, output_active, utype, backend);
1058 }
1059
1060
1061 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1062                                                           UpdateType utype, TocBackend & backend) const
1063 {
1064         DocIterator dit = cdit;
1065         // This also ensures that any document has a table of contents
1066         shared_ptr<Toc> toc = backend.toc("tableofcontents");
1067
1068         BufferParams const & bufparams = buffer_->params();
1069         int const min_toclevel = bufparams.documentClass().min_toclevel();
1070         // we really should have done this before we got here, but it
1071         // can't hurt too much to do it again
1072         bool const doing_output = output_active && producesOutput();
1073
1074         // For each paragraph,
1075         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1076         //   paragraphs as needed.
1077         // * Traverse its insets and let them add their toc items
1078         // * Compute the main table of contents (this is hardcoded)
1079         // * Add the list of changes
1080         ParagraphList const & pars = paragraphs();
1081         pit_type pend = paragraphs().size();
1082         // Record pairs {start,end} of where a toc item was opened for a paragraph
1083         // and where it must be closed
1084         stack<pair<pit_type, pit_type>> addtotoc_stack;
1085
1086         for (pit_type pit = 0; pit != pend; ++pit) {
1087                 Paragraph const & par = pars[pit];
1088                 dit.pit() = pit;
1089                 dit.pos() = 0;
1090
1091                 // Custom AddToToc in paragraph layouts (i.e. theorems)
1092                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1093                         pit_type end =
1094                                 openAddToTocForParagraph(pit, dit, output_active, backend);
1095                         addtotoc_stack.push({pit, end});
1096                 }
1097
1098                 // If we find an InsetArgument that is supposed to provide the TOC caption,
1099                 // we'll save it for use later.
1100                 InsetArgument const * arginset = nullptr;
1101                 for (auto const & table : par.insetList()) {
1102                         dit.pos() = table.pos;
1103                         table.inset->addToToc(dit, doing_output, utype, backend);
1104                         if (InsetArgument const * x = table.inset->asInsetArgument())
1105                                 if (x->isTocCaption())
1106                                         arginset = x;
1107                 }
1108
1109                 // End custom AddToToc in paragraph layouts
1110                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1111                         // execute the closing function
1112                         closeAddToTocForParagraph(addtotoc_stack.top().first,
1113                                                   addtotoc_stack.top().second, backend);
1114                         addtotoc_stack.pop();
1115                 }
1116
1117                 // now the toc entry for the paragraph in the main table of contents
1118                 int const toclevel = text().getTocLevel(pit);
1119                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1120                         // insert this into the table of contents
1121                         docstring tocstring;
1122                         int const length = (doing_output && utype == OutputUpdate) ?
1123                                 INT_MAX : TOC_ENTRY_LENGTH;
1124                         if (arginset) {
1125                                 tocstring = par.labelString();
1126                                 if (!tocstring.empty())
1127                                         tocstring += ' ';
1128                                 arginset->text().forOutliner(tocstring, length);
1129                         } else
1130                                 par.forOutliner(tocstring, length);
1131                         dit.pos() = 0;
1132                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1133                                                tocstring, doing_output));
1134                 }
1135
1136                 // And now the list of changes.
1137                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1138         }
1139 }
1140
1141
1142 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1143                                              DocIterator const & dit,
1144                                              bool output_active,
1145                                              TocBackend & backend) const
1146 {
1147         Paragraph const & par = paragraphs()[pit];
1148         TocBuilder & b = backend.builder(par.layout().tocType());
1149         docstring const & label = par.labelString();
1150         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1151         return text().lastInSequence(pit);
1152 }
1153
1154
1155 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1156                                           TocBackend & backend) const
1157 {
1158         Paragraph const & par = paragraphs()[start];
1159         TocBuilder & b = backend.builder(par.layout().tocType());
1160         if (par.layout().isTocCaption()) {
1161                 docstring str;
1162                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1163                 b.argumentItem(str);
1164         }
1165         b.pop();
1166 }
1167
1168
1169 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1170 {
1171         if (buffer().isClean())
1172                 return Inset::notifyCursorLeaves(old, cur);
1173
1174         // find text inset in old cursor
1175         Cursor insetCur = old;
1176         int scriptSlice = insetCur.find(this);
1177         // we can try to continue here. returning true means
1178         // the cursor is "now" invalid. which it was.
1179         LASSERT(scriptSlice != -1, return true);
1180         insetCur.cutOff(scriptSlice);
1181         LASSERT(&insetCur.inset() == this, return true);
1182
1183         // update the old paragraph's words
1184         insetCur.paragraph().updateWords();
1185
1186         return Inset::notifyCursorLeaves(old, cur);
1187 }
1188
1189
1190 bool InsetText::completionSupported(Cursor const & cur) const
1191 {
1192         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1193         return text_.completionSupported(cur);
1194 }
1195
1196
1197 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1198 {
1199         return completionSupported(cur);
1200 }
1201
1202
1203 bool InsetText::automaticInlineCompletion() const
1204 {
1205         return lyxrc.completion_inline_text;
1206 }
1207
1208
1209 bool InsetText::automaticPopupCompletion() const
1210 {
1211         return lyxrc.completion_popup_text;
1212 }
1213
1214
1215 bool InsetText::showCompletionCursor() const
1216 {
1217         return lyxrc.completion_cursor_text &&
1218                 (lyxrc.completion_inline_text || lyxrc.completion_popup_text);
1219 }
1220
1221
1222 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1223 {
1224         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1225 }
1226
1227
1228 docstring InsetText::completionPrefix(Cursor const & cur) const
1229 {
1230         if (!completionSupported(cur))
1231                 return docstring();
1232         return text_.completionPrefix(cur);
1233 }
1234
1235
1236 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1237         bool finished)
1238 {
1239         if (!completionSupported(cur))
1240                 return false;
1241
1242         return text_.insertCompletion(cur, s, finished);
1243 }
1244
1245
1246 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1247         Dimension & dim) const
1248 {
1249         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1250         tm.completionPosAndDim(cur, x, y, dim);
1251 }
1252
1253
1254 string InsetText::contextMenu(BufferView const &, int, int) const
1255 {
1256         string context_menu = contextMenuName();
1257         if (context_menu != InsetText::contextMenuName())
1258                 context_menu += ";" + InsetText::contextMenuName();
1259         return context_menu;
1260 }
1261
1262
1263 string InsetText::contextMenuName() const
1264 {
1265         return "context-edit";
1266 }
1267
1268
1269 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1270 {
1271         OutputParams rp(&buffer().params().encoding());
1272         rp.for_tooltip = true;
1273         odocstringstream oss;
1274         oss << prefix;
1275
1276         ParagraphList::const_iterator beg = paragraphs().begin();
1277         ParagraphList::const_iterator end = paragraphs().end();
1278         ParagraphList::const_iterator it = beg;
1279         bool ref_printed = false;
1280
1281         for (; it != end; ++it) {
1282                 if (it != beg)
1283                         oss << '\n';
1284                 if ((*it).isRTL(buffer().params()))
1285                         oss << "<div dir=\"rtl\">";
1286                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1287                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1288                         break;
1289         }
1290         docstring str = oss.str();
1291         if (isChanged())
1292                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1293         support::truncateWithEllipsis(str, len);
1294         return str;
1295 }
1296
1297
1298 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1299 {
1300         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1301 }
1302
1303
1304 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1305 {
1306         // Nested cprotect content needs \cprotect
1307         // on each level
1308         if (producesOutput() && hasCProtectContent(fragile))
1309                 return true;
1310
1311         // Environments generally need cprotection in fragile context
1312         if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1313                 return true;
1314
1315         if (!getLayout().needsCProtect())
1316                 return false;
1317
1318         // Environments and "no latex" types (e.g., knitr chunks)
1319         // need cprotection regardless the content
1320         if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1321                 return true;
1322
1323         // If the inset does not produce output (e.g. Note or Branch),
1324         // we can ignore the contained paragraphs
1325         if (!producesOutput())
1326                 return false;
1327
1328         // Commands need cprotection if they contain specific chars
1329         int const nchars_escape = 9;
1330         static char_type const chars_escape[nchars_escape] = {
1331                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1332
1333         ParagraphList const & pars = paragraphs();
1334         pit_type pend = pit_type(paragraphs().size());
1335
1336         for (pit_type pit = 0; pit != pend; ++pit) {
1337                 Paragraph const & par = pars[size_type(pit)];
1338                 if (par.needsCProtection(fragile))
1339                         return true;
1340                 docstring const par_str = par.asString();
1341                 for (int k = 0; k < nchars_escape; k++) {
1342                         if (contains(par_str, chars_escape[k]))
1343                                 return true;
1344                 }
1345         }
1346         return false;
1347 }
1348
1349 } // namespace lyx