]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
3d7de487f6d1b224327d4bc36a999e8079ed75a8
[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 "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_xhtml.h"
42 #include "OutputParams.h"
43 #include "output_plaintext.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Row.h"
48 #include "sgml.h"
49 #include "TexRow.h"
50 #include "texstream.h"
51 #include "TextClass.h"
52 #include "Text.h"
53 #include "TextMetrics.h"
54 #include "TocBackend.h"
55
56 #include "frontends/alert.h"
57 #include "frontends/Painter.h"
58
59 #include "support/bind.h"
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/RefChanger.h"
66
67 #include <algorithm>
68
69
70 using namespace std;
71 using namespace lyx::support;
72
73
74 namespace lyx {
75
76 using graphics::PreviewLoader;
77
78
79 /////////////////////////////////////////////////////////////////////
80
81 InsetText::InsetText(Buffer * buf, UsePlain type)
82         : Inset(buf), drawFrame_(false), is_changed_(false), 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           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 = make_change(pi.background_color,
232                                             pi.backgroundColor(this, false));
233                 // The change tracking cue must not be inherited
234                 Changer dummy2 = make_change(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.finishUndo();
283 }
284
285
286 Inset * InsetText::editXY(Cursor & cur, int x, int y)
287 {
288         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
289 }
290
291
292 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
293 {
294         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
295
296         // See bug #9042, for instance.
297         if (isPassThru()) {
298                 // Force any new text to latex_language FIXME: This
299                 // should only be necessary in constructor, but new
300                 // paragraphs that are created by pressing enter at
301                 // the start of an existing paragraph get the buffer
302                 // language and not latex_language, so we take this
303                 // brute force approach.
304                 cur.current_font.setLanguage(latex_language);
305                 cur.real_current_font.setLanguage(latex_language);
306         }
307
308         switch (cmd.action()) {
309         case LFUN_PASTE:
310         case LFUN_CLIPBOARD_PASTE:
311         case LFUN_SELECTION_PASTE:
312         case LFUN_PRIMARY_SELECTION_PASTE:
313                 text_.dispatch(cur, cmd);
314                 // If we we can only store plain text, we must reset all
315                 // attributes.
316                 // FIXME: Change only the pasted paragraphs
317                 fixParagraphsFont();
318                 break;
319
320         case LFUN_INSET_DISSOLVE: {
321                 bool const main_inset = text_.isMainText();
322                 bool const target_inset = cmd.argument().empty()
323                         || cmd.getArg(0) == insetName(lyxCode());
324
325                 if (!main_inset && target_inset) {
326                         // Text::dissolveInset assumes that the cursor
327                         // is inside the Inset.
328                         if (&cur.inset() != this)
329                                 cur.pushBackward(*this);
330                         cur.beginUndoGroup();
331                         text_.dispatch(cur, cmd);
332                         cur.endUndoGroup();
333                 } else
334                         cur.undispatched();
335                 break;
336         }
337
338         default:
339                 text_.dispatch(cur, cmd);
340         }
341
342         if (!cur.result().dispatched())
343                 Inset::doDispatch(cur, cmd);
344 }
345
346
347 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
348         FuncStatus & status) const
349 {
350         switch (cmd.action()) {
351         case LFUN_INSET_DISSOLVE: {
352                 bool const main_inset = text_.isMainText();
353                 bool const target_inset = cmd.argument().empty()
354                         || cmd.getArg(0) == insetName(lyxCode());
355
356                 if (target_inset)
357                         status.setEnabled(!main_inset);
358                 return target_inset;
359         }
360
361         case LFUN_ARGUMENT_INSERT: {
362                 string const arg = cmd.getArg(0);
363                 if (arg.empty()) {
364                         status.setEnabled(false);
365                         return true;
366                 }
367                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
368                         return text_.getStatus(cur, cmd, status);
369
370                 Layout::LaTeXArgMap args = getLayout().args();
371                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
372                 if (lait != args.end()) {
373                         status.setEnabled(true);
374                         for (Paragraph const & par : paragraphs())
375                                 for (auto const & table : par.insetList())
376                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
377                                                 if (ins->name() == arg) {
378                                                         // we have this already
379                                                         status.setEnabled(false);
380                                                         return true;
381                                                 }
382                 } else
383                         status.setEnabled(false);
384                 return true;
385         }
386
387         default:
388                 // Dispatch only to text_ if the cursor is inside
389                 // the text_. It is not for context menus (bug 5797).
390                 bool ret = false;
391                 if (cur.text() == &text_)
392                         ret = text_.getStatus(cur, cmd, status);
393
394                 if (!ret)
395                         ret = Inset::getStatus(cur, cmd, status);
396                 return ret;
397         }
398 }
399
400
401 void InsetText::fixParagraphsFont()
402 {
403         Font font(inherit_font, buffer().params().language);
404         font.setLanguage(latex_language);
405         ParagraphList::iterator par = paragraphs().begin();
406         ParagraphList::iterator const end = paragraphs().end();
407         while (par != end) {
408                 if (par->isPassThru())
409                         par->resetFonts(font);
410                 if (!par->allowParagraphCustomization())
411                         par->params().clear();
412                 ++par;
413         }
414 }
415
416
417 // bool InsetText::isChanged() const
418 // {
419 //      ParagraphList::const_iterator pit = paragraphs().begin();
420 //      ParagraphList::const_iterator end = paragraphs().end();
421 //      for (; pit != end; ++pit) {
422 //              if (pit->isChanged())
423 //                      return true;
424 //      }
425 //      return false;
426 // }
427
428
429 void InsetText::setChange(Change const & change)
430 {
431         ParagraphList::iterator pit = paragraphs().begin();
432         ParagraphList::iterator end = paragraphs().end();
433         for (; pit != end; ++pit) {
434                 pit->setChange(change);
435         }
436 }
437
438
439 void InsetText::acceptChanges()
440 {
441         text_.acceptChanges();
442 }
443
444
445 void InsetText::rejectChanges()
446 {
447         text_.rejectChanges();
448 }
449
450
451 void InsetText::validate(LaTeXFeatures & features) const
452 {
453         features.useInsetLayout(getLayout());
454         for (Paragraph const & p : paragraphs())
455                 p.validate(features);
456 }
457
458
459 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
460 {
461         // This implements the standard way of handling the LaTeX
462         // output of a text inset, either a command or an
463         // environment. Standard collapsible insets should not
464         // redefine this, non-standard ones may call this.
465         InsetLayout const & il = getLayout();
466         if (il.forceOwnlines())
467                 os << breakln;
468         bool needendgroup = false;
469         if (!il.latexname().empty()) {
470                 if (il.latextype() == InsetLayout::COMMAND) {
471                         // FIXME UNICODE
472                         // FIXME \protect should only be used for fragile
473                         //    commands, but we do not provide this information yet.
474                         if (hasCProtectContent(runparams.moving_arg)) {
475                                 if (contains(runparams.active_chars, '^')) {
476                                         // cprotect relies on ^ being on catcode 7
477                                         os << "\\begingroup\\catcode`\\^=7";
478                                         needendgroup = true;
479                                 }
480                                 os << "\\cprotect";
481                         } else if (runparams.moving_arg)
482                                 os << "\\protect";
483                         os << '\\' << from_utf8(il.latexname());
484                         if (!il.latexargs().empty())
485                                 getArgs(os, runparams);
486                         if (!il.latexparam().empty())
487                                 os << from_utf8(il.latexparam());
488                         os << '{';
489                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
490                         if (il.isDisplay())
491                                 os << breakln;
492                         else
493                                 os << safebreakln;
494                         if (runparams.lastid != -1)
495                                 os.texrow().start(runparams.lastid,
496                                                   runparams.lastpos);
497                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
498                         if (!il.latexargs().empty())
499                                 getArgs(os, runparams);
500                         if (!il.latexparam().empty())
501                                 os << from_utf8(il.latexparam());
502                         os << '\n';
503                 }
504         } else {
505                 if (!il.latexargs().empty())
506                         getArgs(os, runparams);
507                 if (!il.latexparam().empty())
508                         os << from_utf8(il.latexparam());
509         }
510
511         if (!il.leftdelim().empty())
512                 os << il.leftdelim();
513
514         OutputParams rp = runparams;
515         if (isPassThru())
516                 rp.pass_thru = true;
517         if (il.isNeedProtect())
518                 rp.moving_arg = true;
519         if (il.isNeedMBoxProtect())
520                 ++rp.inulemcmd;
521         if (!il.passThruChars().empty())
522                 rp.pass_thru_chars += il.passThruChars();
523         if (!il.newlineCmd().empty())
524                 rp.newlinecmd = il.newlineCmd();
525         rp.par_begin = 0;
526         rp.par_end = paragraphs().size();
527
528         // Output the contents of the inset
529         latexParagraphs(buffer(), text_, os, rp);
530         runparams.encoding = rp.encoding;
531         // Pass the post_macros upstream
532         runparams.post_macro = rp.post_macro;
533
534         if (!il.rightdelim().empty())
535                 os << il.rightdelim();
536
537         if (!il.latexname().empty()) {
538                 if (il.latextype() == InsetLayout::COMMAND) {
539                         os << "}";
540                         if (!il.postcommandargs().empty())
541                                 getArgs(os, runparams, true);
542                         if (needendgroup)
543                                 os << "\\endgroup";
544                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
545                         // A comment environment doesn't need a % before \n\end
546                         if (il.isDisplay() || runparams.inComment)
547                                 os << breakln;
548                         else
549                                 os << safebreakln;
550                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
551                         if (!il.isDisplay())
552                                 os.protectSpace(true);
553                 }
554         }
555         if (il.forceOwnlines())
556                 os << breakln;
557 }
558
559
560 int InsetText::plaintext(odocstringstream & os,
561         OutputParams const & runparams, size_t max_length) const
562 {
563         ParagraphList::const_iterator beg = paragraphs().begin();
564         ParagraphList::const_iterator end = paragraphs().end();
565         ParagraphList::const_iterator it = beg;
566         bool ref_printed = false;
567         int len = 0;
568         for (; it != end; ++it) {
569                 if (it != beg) {
570                         os << '\n';
571                         if (runparams.linelen > 0)
572                                 os << '\n';
573                 }
574                 odocstringstream oss;
575                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
576                 docstring const str = oss.str();
577                 os << str;
578                 // FIXME: len is not computed fully correctly; in principle,
579                 // we have to count the characters after the last '\n'
580                 len = str.size();
581                 if (os.str().size() >= max_length)
582                         break;
583         }
584
585         return len;
586 }
587
588
589 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
590 {
591         ParagraphList::const_iterator const beg = paragraphs().begin();
592
593         if (!undefined())
594                 sgml::openTag(os, getLayout().latexname(),
595                               beg->getID(buffer(), runparams) + getLayout().latexparam());
596
597         docbookParagraphs(text_, buffer(), os, runparams);
598
599         if (!undefined())
600                 sgml::closeTag(os, getLayout().latexname());
601
602         return 0;
603 }
604
605
606 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
607 {
608         return insetAsXHTML(xs, runparams, WriteEverything);
609 }
610
611
612 // FIXME XHTML
613 // There are cases where we may need to close open fonts and such
614 // and then re-open them when we are done. This would be the case, e.g.,
615 // if we were otherwise about to write:
616 //              <em>word <div class='foot'>footnote text.</div> emph</em>
617 // The problem isn't so much that the footnote text will get emphasized:
618 // we can handle that with CSS. The problem is that this is invalid XHTML.
619 // One solution would be to make the footnote <span>, but the problem is
620 // completely general, and so we'd have to make absolutely everything into
621 // span. What I think will work is to check if we're about to write "div" and,
622 // if so, try to close fonts, etc.
623 // There are probably limits to how well we can do here, though, and we will
624 // have to rely upon users not putting footnotes inside noun-type insets.
625 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
626                                   XHTMLOptions opts) const
627 {
628         // we will always want to output all our paragraphs when we are
629         // called this way.
630         OutputParams runparams = rp;
631         runparams.par_begin = 0;
632         runparams.par_end = text().paragraphs().size();
633
634         if (undefined()) {
635                 xs.startDivision(false);
636                 xhtmlParagraphs(text_, buffer(), xs, runparams);
637                 xs.endDivision();
638                 return docstring();
639         }
640
641         InsetLayout const & il = getLayout();
642         if (opts & WriteOuterTag)
643                 xs << html::StartTag(il.htmltag(), il.htmlattr());
644
645         if ((opts & WriteLabel) && !il.counter().empty()) {
646                 BufferParams const & bp = buffer().masterBuffer()->params();
647                 Counters & cntrs = bp.documentClass().counters();
648                 cntrs.step(il.counter(), OutputUpdate);
649                 // FIXME: translate to paragraph language
650                 if (!il.htmllabel().empty()) {
651                         docstring const lbl =
652                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
653                         // FIXME is this check necessary?
654                         if (!lbl.empty()) {
655                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
656                                 xs << lbl;
657                                 xs << html::EndTag(il.htmllabeltag());
658                         }
659                 }
660         }
661
662         if (opts & WriteInnerTag)
663                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
664
665         // we will eventually lose information about the containing inset
666         if (!allowMultiPar() || opts == JustText)
667                 runparams.html_make_pars = false;
668         if (il.isPassThru())
669                 runparams.pass_thru = true;
670
671         xs.startDivision(false);
672         xhtmlParagraphs(text_, buffer(), xs, runparams);
673         xs.endDivision();
674
675         if (opts & WriteInnerTag)
676                 xs << html::EndTag(il.htmlinnertag());
677
678         if (opts & WriteOuterTag)
679                 xs << html::EndTag(il.htmltag());
680
681         return docstring();
682 }
683
684
685 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
686                         bool const post) const
687 {
688         OutputParams runparams = runparams_in;
689         runparams.local_font =
690                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
691         if (isPassThru())
692                 runparams.pass_thru = true;
693         if (post)
694                 latexArgInsetsForParent(paragraphs(), os, runparams,
695                                         getLayout().postcommandargs(), "post:");
696         else
697                 latexArgInsetsForParent(paragraphs(), os, runparams,
698                                         getLayout().latexargs());
699 }
700
701
702 void InsetText::cursorPos(BufferView const & bv,
703                 CursorSlice const & sl, bool boundary, int & x, int & y) const
704 {
705         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
706         y = bv.textMetrics(&text_).cursorY(sl, boundary);
707 }
708
709
710 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
711 {
712         clear();
713         Paragraph & first = paragraphs().front();
714         for (unsigned int i = 0; i < data.length(); ++i)
715                 first.insertChar(i, data[i], font, trackChanges);
716 }
717
718
719 void InsetText::setDrawFrame(bool flag)
720 {
721         drawFrame_ = flag;
722 }
723
724
725 ColorCode InsetText::frameColor() const
726 {
727         return frame_color_;
728 }
729
730
731 void InsetText::setFrameColor(ColorCode col)
732 {
733         frame_color_ = col;
734 }
735
736
737 void InsetText::appendParagraphs(ParagraphList & plist)
738 {
739         // There is little we can do here to keep track of changes.
740         // As of 2006/10/20, appendParagraphs is used exclusively by
741         // LyXTabular::setMultiColumn. In this context, the paragraph break
742         // is lost irreversibly and the appended text doesn't really change
743
744         ParagraphList & pl = paragraphs();
745
746         ParagraphList::iterator pit = plist.begin();
747         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
748         ++pit;
749         mergeParagraph(buffer().params(), pl,
750                        distance(pl.begin(), ins) - 1);
751
752         for_each(pit, plist.end(),
753                  bind(&ParagraphList::push_back, ref(pl), _1));
754 }
755
756
757 void InsetText::addPreview(DocIterator const & text_inset_pos,
758         PreviewLoader & loader) const
759 {
760         ParagraphList::const_iterator pit = paragraphs().begin();
761         ParagraphList::const_iterator pend = paragraphs().end();
762         int pidx = 0;
763
764         DocIterator inset_pos = text_inset_pos;
765         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
766
767         for (; pit != pend; ++pit, ++pidx) {
768                 InsetList::const_iterator it  = pit->insetList().begin();
769                 InsetList::const_iterator end = pit->insetList().end();
770                 inset_pos.pit() = pidx;
771                 for (; it != end; ++it) {
772                         inset_pos.pos() = it->pos;
773                         it->inset->addPreview(inset_pos, loader);
774                 }
775         }
776 }
777
778
779 ParagraphList const & InsetText::paragraphs() const
780 {
781         return text_.paragraphs();
782 }
783
784
785 ParagraphList & InsetText::paragraphs()
786 {
787         return text_.paragraphs();
788 }
789
790
791 bool InsetText::hasCProtectContent(bool fragile) const
792 {
793         fragile |= getLayout().isNeedProtect();
794         ParagraphList const & pars = paragraphs();
795         pit_type pend = pit_type(paragraphs().size());
796         for (pit_type pit = 0; pit != pend; ++pit) {
797                 Paragraph const & par = pars[size_type(pit)];
798                 if (par.needsCProtection(fragile))
799                         return true;
800         }
801         return false;
802 }
803
804
805 bool InsetText::insetAllowed(InsetCode code) const
806 {
807         switch (code) {
808         // Arguments and (plain) quotes are also allowed in PassThru insets
809         case ARG_CODE:
810         case QUOTE_CODE:
811                 return true;
812         default:
813                 return !isPassThru();
814         }
815 }
816
817
818 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
819 {
820         ParIterator it2 = it;
821         it2.forwardPos();
822         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
823         if (producesOutput()) {
824                 InsetLayout const & il = getLayout();
825                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
826                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
827                 if (save_layouts) {
828                         // LYXERR0("Entering " << name());
829                         cnt.clearLastLayout();
830                         // FIXME cnt.saveLastCounter()?
831                 }
832                 buffer().updateBuffer(it2, utype, deleted);
833                 if (save_layouts) {
834                         // LYXERR0("Exiting " << name());
835                         cnt.restoreLastLayout();
836                         // FIXME cnt.restoreLastCounter()?
837                 }
838         } else {
839                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
840                 // Note that we do not need to call:
841                 //      tclass.counters().clearLastLayout()
842                 // since we are saving and restoring the existing counters, etc.
843                 Counters savecnt = tclass.counters();
844                 tclass.counters().reset();
845                 // we need float information even in note insets (#9760)
846                 tclass.counters().current_float(savecnt.current_float());
847                 tclass.counters().isSubfloat(savecnt.isSubfloat());
848                 buffer().updateBuffer(it2, utype, deleted);
849                 tclass.counters() = move(savecnt);
850         }
851 }
852
853
854 void InsetText::toString(odocstream & os) const
855 {
856         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
857 }
858
859
860 void InsetText::forOutliner(docstring & os, size_t const maxlen,
861                                                         bool const shorten) const
862 {
863         if (!getLayout().isInToc())
864                 return;
865         text().forOutliner(os, maxlen, shorten);
866 }
867
868
869 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
870                                                  UpdateType utype, TocBackend & backend) const
871 {
872         DocIterator dit = cdit;
873         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
874         iterateForToc(dit, output_active, utype, backend);
875 }
876
877
878 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
879                                                           UpdateType utype, TocBackend & backend) const
880 {
881         DocIterator dit = cdit;
882         // This also ensures that any document has a table of contents
883         shared_ptr<Toc> toc = backend.toc("tableofcontents");
884
885         BufferParams const & bufparams = buffer_->params();
886         int const min_toclevel = bufparams.documentClass().min_toclevel();
887         // we really should have done this before we got here, but it
888         // can't hurt too much to do it again
889         bool const doing_output = output_active && producesOutput();
890
891         // For each paragraph,
892         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
893         //   paragraphs as needed.
894         // * Traverse its insets and let them add their toc items
895         // * Compute the main table of contents (this is hardcoded)
896         // * Add the list of changes
897         ParagraphList const & pars = paragraphs();
898         pit_type pend = paragraphs().size();
899         // Record pairs {start,end} of where a toc item was opened for a paragraph
900         // and where it must be closed
901         stack<pair<pit_type, pit_type>> addtotoc_stack;
902
903         for (pit_type pit = 0; pit != pend; ++pit) {
904                 Paragraph const & par = pars[pit];
905                 dit.pit() = pit;
906                 dit.pos() = 0;
907
908                 // Custom AddToToc in paragraph layouts (i.e. theorems)
909                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
910                         pit_type end =
911                                 openAddToTocForParagraph(pit, dit, output_active, backend);
912                         addtotoc_stack.push({pit, end});
913                 }
914
915                 // If we find an InsetArgument that is supposed to provide the TOC caption,
916                 // we'll save it for use later.
917                 InsetArgument const * arginset = nullptr;
918                 for (auto const & table : par.insetList()) {
919                         dit.pos() = table.pos;
920                         table.inset->addToToc(dit, doing_output, utype, backend);
921                         if (InsetArgument const * x = table.inset->asInsetArgument())
922                                 if (x->isTocCaption())
923                                         arginset = x;
924                 }
925
926                 // End custom AddToToc in paragraph layouts
927                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
928                         // execute the closing function
929                         closeAddToTocForParagraph(addtotoc_stack.top().first,
930                                                   addtotoc_stack.top().second, backend);
931                         addtotoc_stack.pop();
932                 }
933
934                 // now the toc entry for the paragraph in the main table of contents
935                 int const toclevel = text().getTocLevel(pit);
936                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
937                         // insert this into the table of contents
938                         docstring tocstring;
939                         int const length = (doing_output && utype == OutputUpdate) ?
940                                 INT_MAX : TOC_ENTRY_LENGTH;
941                         if (arginset) {
942                                 tocstring = par.labelString();
943                                 if (!tocstring.empty())
944                                         tocstring += ' ';
945                                 arginset->text().forOutliner(tocstring, length);
946                         } else
947                                 par.forOutliner(tocstring, length);
948                         dit.pos() = 0;
949                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
950                                                tocstring, doing_output));
951                 }
952
953                 // And now the list of changes.
954                 par.addChangesToToc(dit, buffer(), doing_output, backend);
955         }
956 }
957
958
959 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
960                                              DocIterator const & dit,
961                                              bool output_active,
962                                              TocBackend & backend) const
963 {
964         Paragraph const & par = paragraphs()[pit];
965         TocBuilder & b = backend.builder(par.layout().tocType());
966         docstring const label = par.labelString();
967         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
968         return text().lastInSequence(pit);
969 }
970
971
972 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
973                                           TocBackend & backend) const
974 {
975         Paragraph const & par = paragraphs()[start];
976         TocBuilder & b = backend.builder(par.layout().tocType());
977         if (par.layout().isTocCaption()) {
978                 docstring str;
979                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
980                 b.argumentItem(str);
981         }
982         b.pop();
983 }
984
985
986 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
987 {
988         if (buffer().isClean())
989                 return Inset::notifyCursorLeaves(old, cur);
990
991         // find text inset in old cursor
992         Cursor insetCur = old;
993         int scriptSlice = insetCur.find(this);
994         // we can try to continue here. returning true means
995         // the cursor is "now" invalid. which it was.
996         LASSERT(scriptSlice != -1, return true);
997         insetCur.cutOff(scriptSlice);
998         LASSERT(&insetCur.inset() == this, return true);
999
1000         // update the old paragraph's words
1001         insetCur.paragraph().updateWords();
1002
1003         return Inset::notifyCursorLeaves(old, cur);
1004 }
1005
1006
1007 bool InsetText::completionSupported(Cursor const & cur) const
1008 {
1009         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1010         return text_.completionSupported(cur);
1011 }
1012
1013
1014 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1015 {
1016         return completionSupported(cur);
1017 }
1018
1019
1020 bool InsetText::automaticInlineCompletion() const
1021 {
1022         return lyxrc.completion_inline_text;
1023 }
1024
1025
1026 bool InsetText::automaticPopupCompletion() const
1027 {
1028         return lyxrc.completion_popup_text;
1029 }
1030
1031
1032 bool InsetText::showCompletionCursor() const
1033 {
1034         return lyxrc.completion_cursor_text;
1035 }
1036
1037
1038 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1039 {
1040         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1041 }
1042
1043
1044 docstring InsetText::completionPrefix(Cursor const & cur) const
1045 {
1046         if (!completionSupported(cur))
1047                 return docstring();
1048         return text_.completionPrefix(cur);
1049 }
1050
1051
1052 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1053         bool finished)
1054 {
1055         if (!completionSupported(cur))
1056                 return false;
1057
1058         return text_.insertCompletion(cur, s, finished);
1059 }
1060
1061
1062 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1063         Dimension & dim) const
1064 {
1065         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1066         tm.completionPosAndDim(cur, x, y, dim);
1067 }
1068
1069
1070 string InsetText::contextMenu(BufferView const &, int, int) const
1071 {
1072         string context_menu = contextMenuName();
1073         if (context_menu != InsetText::contextMenuName())
1074                 context_menu += ";" + InsetText::contextMenuName();
1075         return context_menu;
1076 }
1077
1078
1079 string InsetText::contextMenuName() const
1080 {
1081         return "context-edit";
1082 }
1083
1084
1085 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1086 {
1087         OutputParams rp(&buffer().params().encoding());
1088         rp.for_tooltip = true;
1089         odocstringstream oss;
1090         oss << prefix;
1091
1092         ParagraphList::const_iterator beg = paragraphs().begin();
1093         ParagraphList::const_iterator end = paragraphs().end();
1094         ParagraphList::const_iterator it = beg;
1095         bool ref_printed = false;
1096
1097         for (; it != end; ++it) {
1098                 if (it != beg)
1099                         oss << '\n';
1100                 if ((*it).isRTL(buffer().params()))
1101                         oss << "<div dir=\"rtl\">";
1102                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1103                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1104                         break;
1105         }
1106         docstring str = oss.str();
1107         if (isChanged())
1108                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1109         support::truncateWithEllipsis(str, len);
1110         return str;
1111 }
1112
1113
1114 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1115 {
1116         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1117 }
1118
1119
1120 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1121 {
1122         // Nested cprotect content needs \cprotect
1123         // on each level
1124         if (producesOutput() && hasCProtectContent(fragile))
1125                 return true;
1126
1127         // Environments generally need cprotection in fragile context
1128         if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1129                 return true;
1130
1131         if (!getLayout().needsCProtect())
1132                 return false;
1133
1134         // Environments and "no latex" types (e.g., knitr chunks)
1135         // need cprotection regardless the content
1136         if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1137                 return true;
1138
1139         // If the inset does not produce output (e.g. Note or Branch),
1140         // we can ignore the contained paragraphs
1141         if (!producesOutput())
1142                 return false;
1143
1144         // Commands need cprotection if they contain specific chars
1145         int const nchars_escape = 9;
1146         static char_type const chars_escape[nchars_escape] = {
1147                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1148
1149         ParagraphList const & pars = paragraphs();
1150         pit_type pend = pit_type(paragraphs().size());
1151
1152         for (pit_type pit = 0; pit != pend; ++pit) {
1153                 Paragraph const & par = pars[size_type(pit)];
1154                 if (par.needsCProtection(fragile))
1155                         return true;
1156                 docstring const par_str = par.asString();
1157                 for (int k = 0; k < nchars_escape; k++) {
1158                         if (contains(par_str, chars_escape[k]))
1159                                 return true;
1160                 }
1161         }
1162         return false;
1163 }
1164
1165 } // namespace lyx