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