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