]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Add basic support for cprotect
[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_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), frame_color_(Color_insetframe),
83         text_(this, type == DefaultLayout)
84 {
85 }
86
87
88 InsetText::InsetText(InsetText const & in)
89         : Inset(in), text_(this, in.text_)
90 {
91         drawFrame_ = in.drawFrame_;
92         frame_color_ = in.frame_color_;
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.dimension();
144         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
145         dim.des += TEXT_TO_INSET_OFFSET;
146         dim.asc += TEXT_TO_INSET_OFFSET;
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         // Hand font through to contained lyxtext:
194         tm.font_.fontInfo() = mi.base.font;
195         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
196
197         // This can happen when a layout has a left and right margin,
198         // and the view is made very narrow. We can't do better than
199         // to draw it partly out of view (bug 5890).
200         if (mi.base.textwidth < 1)
201                 mi.base.textwidth = 1;
202
203         if (hasFixedWidth())
204                 tm.metrics(mi, dim, mi.base.textwidth);
205         else
206                 tm.metrics(mi, dim);
207         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
208         dim.asc += TEXT_TO_INSET_OFFSET;
209         dim.des += TEXT_TO_INSET_OFFSET;
210         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
211 }
212
213
214 void InsetText::draw(PainterInfo & pi, int x, int y) const
215 {
216         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
217
218         int const w = tm.width() + TEXT_TO_INSET_OFFSET;
219         int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
220         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
221         int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
222         bool change_drawn = false;
223         if (drawFrame_ || pi.full_repaint) {
224                 if (pi.full_repaint)
225                         pi.pain.fillRectangle(xframe, yframe, w, h,
226                                 pi.backgroundColor(this));
227
228                 // Change color of the frame in tracked changes, like for tabulars.
229                 // Only do so if the color is not custom. But do so even if RowPainter
230                 // handles the strike-through already.
231                 Color c;
232                 if (pi.change_.changed()
233                     // Originally, these are the colors with role Text, from role() in
234                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
235                     // types, and also maybe it need not match in the future.
236                     && (frameColor() == Color_foreground
237                         || frameColor() == Color_cursor
238                         || frameColor() == Color_preview
239                         || frameColor() == Color_tabularline
240                         || frameColor() == Color_previewframe)) {
241                         c = pi.change_.color();
242                         change_drawn = true;
243                 } else
244                         c = frameColor();
245                 if (drawFrame_)
246                         pi.pain.rectangle(xframe, yframe, w, h, c);
247         }
248         {
249                 Changer dummy = make_change(pi.background_color,
250                                             pi.backgroundColor(this, false));
251                 // The change tracking cue must not be inherited
252                 Changer dummy2 = make_change(pi.change_, Change());
253                 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
254         }
255         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
256                 // Do not draw the change tracking cue if already done by RowPainter and
257                 // do not draw the cue for INSERTED if the information is already in the
258                 // color of the frame
259                 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
260 }
261
262
263 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
264 {
265         pit_type const pit = front ? 0 : paragraphs().size() - 1;
266         pos_type pos = front ? 0 : paragraphs().back().size();
267
268         // if visual information is not to be ignored, move to extreme right/left
269         if (entry_from != ENTRY_DIRECTION_IGNORE) {
270                 Cursor temp_cur = cur;
271                 temp_cur.pit() = pit;
272                 temp_cur.pos() = pos;
273                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
274                 pos = temp_cur.pos();
275         }
276
277         cur.top().setPitPos(pit, pos);
278         cur.finishUndo();
279 }
280
281
282 Inset * InsetText::editXY(Cursor & cur, int x, int y)
283 {
284         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
285 }
286
287
288 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
289 {
290         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
291
292         // See bug #9042, for instance.
293         if (isPassThru()) {
294                 // Force any new text to latex_language FIXME: This
295                 // should only be necessary in constructor, but new
296                 // paragraphs that are created by pressing enter at
297                 // the start of an existing paragraph get the buffer
298                 // language and not latex_language, so we take this
299                 // brute force approach.
300                 cur.current_font.setLanguage(latex_language);
301                 cur.real_current_font.setLanguage(latex_language);
302         }
303
304         switch (cmd.action()) {
305         case LFUN_PASTE:
306         case LFUN_CLIPBOARD_PASTE:
307         case LFUN_SELECTION_PASTE:
308         case LFUN_PRIMARY_SELECTION_PASTE:
309                 text_.dispatch(cur, cmd);
310                 // If we we can only store plain text, we must reset all
311                 // attributes.
312                 // FIXME: Change only the pasted paragraphs
313                 fixParagraphsFont();
314                 break;
315
316         case LFUN_INSET_DISSOLVE: {
317                 bool const main_inset = text_.isMainText();
318                 bool const target_inset = cmd.argument().empty()
319                         || cmd.getArg(0) == insetName(lyxCode());
320                 // cur.inset() is the tabular when this is a single cell (bug #9954)
321                 bool const one_cell = cur.inset().nargs() == 1;
322
323                 if (!main_inset && target_inset && one_cell) {
324                         // Text::dissolveInset assumes that the cursor
325                         // is inside the Inset.
326                         if (&cur.inset() != this)
327                                 cur.pushBackward(*this);
328                         cur.beginUndoGroup();
329                         text_.dispatch(cur, cmd);
330                         cur.endUndoGroup();
331                 } else
332                         cur.undispatched();
333                 break;
334         }
335
336         default:
337                 text_.dispatch(cur, cmd);
338         }
339
340         if (!cur.result().dispatched())
341                 Inset::doDispatch(cur, cmd);
342 }
343
344
345 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
346         FuncStatus & status) const
347 {
348         switch (cmd.action()) {
349         case LFUN_INSET_DISSOLVE: {
350                 bool const main_inset = text_.isMainText();
351                 bool const target_inset = cmd.argument().empty()
352                         || cmd.getArg(0) == insetName(lyxCode());
353                 // cur.inset() is the tabular when this is a single cell (bug #9954)
354                 bool const one_cell = cur.inset().nargs() == 1;
355
356                 if (target_inset)
357                         status.setEnabled(!main_inset && one_cell);
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 void InsetText::setChange(Change const & change)
418 {
419         ParagraphList::iterator pit = paragraphs().begin();
420         ParagraphList::iterator end = paragraphs().end();
421         for (; pit != end; ++pit) {
422                 pit->setChange(change);
423         }
424 }
425
426
427 void InsetText::acceptChanges()
428 {
429         text_.acceptChanges();
430 }
431
432
433 void InsetText::rejectChanges()
434 {
435         text_.rejectChanges();
436 }
437
438
439 void InsetText::validate(LaTeXFeatures & features) const
440 {
441         features.useInsetLayout(getLayout());
442         for (Paragraph const & p : paragraphs())
443                 p.validate(features);
444 }
445
446
447 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
448 {
449         // This implements the standard way of handling the LaTeX
450         // output of a text inset, either a command or an
451         // environment. Standard collapsible insets should not
452         // redefine this, non-standard ones may call this.
453         InsetLayout const & il = getLayout();
454         if (il.forceOwnlines())
455                 os << breakln;
456         if (!il.latexname().empty()) {
457                 if (il.latextype() == InsetLayout::COMMAND) {
458                         // FIXME UNICODE
459                         // FIXME \protect should only be used for fragile
460                         //    commands, but we do not provide this information yet.
461                         if (hasCProtectContent())
462                                 os << "\\cprotect";
463                         else if (runparams.moving_arg)
464                                 os << "\\protect";
465                         os << '\\' << from_utf8(il.latexname());
466                         if (!il.latexargs().empty())
467                                 getArgs(os, runparams);
468                         if (!il.latexparam().empty())
469                                 os << from_utf8(il.latexparam());
470                         os << '{';
471                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
472                         if (il.isDisplay())
473                                 os << breakln;
474                         else
475                                 os << safebreakln;
476                         if (runparams.lastid != -1)
477                                 os.texrow().start(runparams.lastid,
478                                                   runparams.lastpos);
479                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
480                         if (!il.latexargs().empty())
481                                 getArgs(os, runparams);
482                         if (!il.latexparam().empty())
483                                 os << from_utf8(il.latexparam());
484                         os << '\n';
485                 }
486         } else {
487                 if (!il.latexargs().empty())
488                         getArgs(os, runparams);
489                 if (!il.latexparam().empty())
490                         os << from_utf8(il.latexparam());
491         }
492
493         if (!il.leftdelim().empty())
494                 os << il.leftdelim();
495
496         OutputParams rp = runparams;
497         if (isPassThru())
498                 rp.pass_thru = true;
499         if (il.isNeedProtect())
500                 rp.moving_arg = true;
501         if (!il.passThruChars().empty())
502                 rp.pass_thru_chars += il.passThruChars();
503         rp.par_begin = 0;
504         rp.par_end = paragraphs().size();
505
506         // Output the contents of the inset
507         latexParagraphs(buffer(), text_, os, rp);
508         runparams.encoding = rp.encoding;
509
510         if (!il.rightdelim().empty())
511                 os << il.rightdelim();
512
513         if (!il.latexname().empty()) {
514                 if (il.latextype() == InsetLayout::COMMAND) {
515                         os << "}";
516                         if (!il.postcommandargs().empty())
517                                 getArgs(os, runparams, true);
518                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
519                         // A comment environment doesn't need a % before \n\end
520                         if (il.isDisplay() || runparams.inComment)
521                                 os << breakln;
522                         else
523                                 os << safebreakln;
524                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
525                         if (!il.isDisplay())
526                                 os.protectSpace(true);
527                 }
528         }
529         if (il.forceOwnlines())
530                 os << breakln;
531 }
532
533
534 int InsetText::plaintext(odocstringstream & os,
535         OutputParams const & runparams, size_t max_length) const
536 {
537         ParagraphList::const_iterator beg = paragraphs().begin();
538         ParagraphList::const_iterator end = paragraphs().end();
539         ParagraphList::const_iterator it = beg;
540         bool ref_printed = false;
541         int len = 0;
542         for (; it != end; ++it) {
543                 if (it != beg) {
544                         os << '\n';
545                         if (runparams.linelen > 0)
546                                 os << '\n';
547                 }
548                 odocstringstream oss;
549                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
550                 docstring const str = oss.str();
551                 os << str;
552                 // FIXME: len is not computed fully correctly; in principle,
553                 // we have to count the characters after the last '\n'
554                 len = str.size();
555                 if (os.str().size() >= max_length)
556                         break;
557         }
558
559         return len;
560 }
561
562
563 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
564 {
565         ParagraphList::const_iterator const beg = paragraphs().begin();
566
567         if (!undefined())
568                 sgml::openTag(os, getLayout().latexname(),
569                               beg->getID(buffer(), runparams) + getLayout().latexparam());
570
571         docbookParagraphs(text_, buffer(), os, runparams);
572
573         if (!undefined())
574                 sgml::closeTag(os, getLayout().latexname());
575
576         return 0;
577 }
578
579
580 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
581 {
582         return insetAsXHTML(xs, runparams, WriteEverything);
583 }
584
585
586 // FIXME XHTML
587 // There are cases where we may need to close open fonts and such
588 // and then re-open them when we are done. This would be the case, e.g.,
589 // if we were otherwise about to write:
590 //              <em>word <div class='foot'>footnote text.</div> emph</em>
591 // The problem isn't so much that the footnote text will get emphasized:
592 // we can handle that with CSS. The problem is that this is invalid XHTML.
593 // One solution would be to make the footnote <span>, but the problem is
594 // completely general, and so we'd have to make absolutely everything into
595 // span. What I think will work is to check if we're about to write "div" and,
596 // if so, try to close fonts, etc.
597 // There are probably limits to how well we can do here, though, and we will
598 // have to rely upon users not putting footnotes inside noun-type insets.
599 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
600                                   XHTMLOptions opts) const
601 {
602         // we will always want to output all our paragraphs when we are
603         // called this way.
604         OutputParams runparams = rp;
605         runparams.par_begin = 0;
606         runparams.par_end = text().paragraphs().size();
607
608         if (undefined()) {
609                 xs.startDivision(false);
610                 xhtmlParagraphs(text_, buffer(), xs, runparams);
611                 xs.endDivision();
612                 return docstring();
613         }
614
615         InsetLayout const & il = getLayout();
616         if (opts & WriteOuterTag)
617                 xs << html::StartTag(il.htmltag(), il.htmlattr());
618
619         if ((opts & WriteLabel) && !il.counter().empty()) {
620                 BufferParams const & bp = buffer().masterBuffer()->params();
621                 Counters & cntrs = bp.documentClass().counters();
622                 cntrs.step(il.counter(), OutputUpdate);
623                 // FIXME: translate to paragraph language
624                 if (!il.htmllabel().empty()) {
625                         docstring const lbl =
626                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
627                         // FIXME is this check necessary?
628                         if (!lbl.empty()) {
629                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
630                                 xs << lbl;
631                                 xs << html::EndTag(il.htmllabeltag());
632                         }
633                 }
634         }
635
636         if (opts & WriteInnerTag)
637                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
638
639         // we will eventually lose information about the containing inset
640         if (!allowMultiPar() || opts == JustText)
641                 runparams.html_make_pars = false;
642         if (il.isPassThru())
643                 runparams.pass_thru = true;
644
645         xs.startDivision(false);
646         xhtmlParagraphs(text_, buffer(), xs, runparams);
647         xs.endDivision();
648
649         if (opts & WriteInnerTag)
650                 xs << html::EndTag(il.htmlinnertag());
651
652         if (opts & WriteOuterTag)
653                 xs << html::EndTag(il.htmltag());
654
655         return docstring();
656 }
657
658
659 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
660                         bool const post) const
661 {
662         OutputParams runparams = runparams_in;
663         runparams.local_font =
664                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
665         if (isPassThru())
666                 runparams.pass_thru = true;
667         if (post)
668                 latexArgInsetsForParent(paragraphs(), os, runparams,
669                                         getLayout().postcommandargs(), "post:");
670         else
671                 latexArgInsetsForParent(paragraphs(), os, runparams,
672                                         getLayout().latexargs());
673 }
674
675
676 void InsetText::cursorPos(BufferView const & bv,
677                 CursorSlice const & sl, bool boundary, int & x, int & y) const
678 {
679         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
680         y = bv.textMetrics(&text_).cursorY(sl, boundary);
681 }
682
683
684 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
685 {
686         clear();
687         Paragraph & first = paragraphs().front();
688         for (unsigned int i = 0; i < data.length(); ++i)
689                 first.insertChar(i, data[i], font, trackChanges);
690 }
691
692
693 void InsetText::setDrawFrame(bool flag)
694 {
695         drawFrame_ = flag;
696 }
697
698
699 ColorCode InsetText::frameColor() const
700 {
701         return frame_color_;
702 }
703
704
705 void InsetText::setFrameColor(ColorCode col)
706 {
707         frame_color_ = col;
708 }
709
710
711 void InsetText::appendParagraphs(ParagraphList & plist)
712 {
713         // There is little we can do here to keep track of changes.
714         // As of 2006/10/20, appendParagraphs is used exclusively by
715         // LyXTabular::setMultiColumn. In this context, the paragraph break
716         // is lost irreversibly and the appended text doesn't really change
717
718         ParagraphList & pl = paragraphs();
719
720         ParagraphList::iterator pit = plist.begin();
721         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
722         ++pit;
723         mergeParagraph(buffer().params(), pl,
724                        distance(pl.begin(), ins) - 1);
725
726         for_each(pit, plist.end(),
727                  bind(&ParagraphList::push_back, ref(pl), _1));
728 }
729
730
731 void InsetText::addPreview(DocIterator const & text_inset_pos,
732         PreviewLoader & loader) const
733 {
734         ParagraphList::const_iterator pit = paragraphs().begin();
735         ParagraphList::const_iterator pend = paragraphs().end();
736         int pidx = 0;
737
738         DocIterator inset_pos = text_inset_pos;
739         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
740
741         for (; pit != pend; ++pit, ++pidx) {
742                 InsetList::const_iterator it  = pit->insetList().begin();
743                 InsetList::const_iterator end = pit->insetList().end();
744                 inset_pos.pit() = pidx;
745                 for (; it != end; ++it) {
746                         inset_pos.pos() = it->pos;
747                         it->inset->addPreview(inset_pos, loader);
748                 }
749         }
750 }
751
752
753 ParagraphList const & InsetText::paragraphs() const
754 {
755         return text_.paragraphs();
756 }
757
758
759 ParagraphList & InsetText::paragraphs()
760 {
761         return text_.paragraphs();
762 }
763
764
765 bool InsetText::hasCProtectContent() const
766 {
767         ParagraphList const & pars = paragraphs();
768         pit_type pend = paragraphs().size();
769         for (pit_type pit = 0; pit != pend; ++pit) {
770                 Paragraph const & par = pars[pit];
771                 if (par.needsCProtection())
772                         return true;
773         }
774         return false;
775 }
776
777
778 bool InsetText::insetAllowed(InsetCode code) const
779 {
780         switch (code) {
781         // Arguments and (plain) quotes are also allowed in PassThru insets
782         case ARG_CODE:
783         case QUOTE_CODE:
784                 return true;
785         default:
786                 return !isPassThru();
787         }
788 }
789
790
791 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
792 {
793         ParIterator it2 = it;
794         it2.forwardPos();
795         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
796         if (producesOutput()) {
797                 InsetLayout const & il = getLayout();
798                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
799                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
800                 if (save_layouts) {
801                         // LYXERR0("Entering " << name());
802                         cnt.clearLastLayout();
803                         // FIXME cnt.saveLastCounter()?
804                 }
805                 buffer().updateBuffer(it2, utype);
806                 if (save_layouts) {
807                         // LYXERR0("Exiting " << name());
808                         cnt.restoreLastLayout();
809                         // FIXME cnt.restoreLastCounter()?
810                 }
811         } else {
812                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
813                 // Note that we do not need to call:
814                 //      tclass.counters().clearLastLayout()
815                 // since we are saving and restoring the existing counters, etc.
816                 Counters const savecnt = tclass.counters();
817                 tclass.counters().reset();
818                 // we need float information even in note insets (#9760)
819                 tclass.counters().current_float(savecnt.current_float());
820                 tclass.counters().isSubfloat(savecnt.isSubfloat());
821                 buffer().updateBuffer(it2, utype);
822                 tclass.counters() = savecnt;
823         }
824 }
825
826
827 void InsetText::toString(odocstream & os) const
828 {
829         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
830 }
831
832
833 void InsetText::forOutliner(docstring & os, size_t const maxlen,
834                                                         bool const shorten) const
835 {
836         if (!getLayout().isInToc())
837                 return;
838         text().forOutliner(os, maxlen, shorten);
839 }
840
841
842 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
843                                                  UpdateType utype, TocBackend & backend) const
844 {
845         DocIterator dit = cdit;
846         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
847         iterateForToc(dit, output_active, utype, backend);
848 }
849
850
851 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
852                                                           UpdateType utype, TocBackend & backend) const
853 {
854         DocIterator dit = cdit;
855         // This also ensures that any document has a table of contents
856         shared_ptr<Toc> toc = backend.toc("tableofcontents");
857
858         BufferParams const & bufparams = buffer_->params();
859         int const min_toclevel = bufparams.documentClass().min_toclevel();
860         // we really should have done this before we got here, but it
861         // can't hurt too much to do it again
862         bool const doing_output = output_active && producesOutput();
863
864         // For each paragraph,
865         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
866         //   paragraphs as needed.
867         // * Traverse its insets and let them add their toc items
868         // * Compute the main table of contents (this is hardcoded)
869         // * Add the list of changes
870         ParagraphList const & pars = paragraphs();
871         pit_type pend = paragraphs().size();
872         // Record pairs {start,end} of where a toc item was opened for a paragraph
873         // and where it must be closed
874         stack<pair<pit_type, pit_type>> addtotoc_stack;
875
876         for (pit_type pit = 0; pit != pend; ++pit) {
877                 Paragraph const & par = pars[pit];
878                 dit.pit() = pit;
879                 dit.pos() = 0;
880
881                 // Custom AddToToc in paragraph layouts (i.e. theorems)
882                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
883                         pit_type end =
884                                 openAddToTocForParagraph(pit, dit, output_active, backend);
885                         addtotoc_stack.push({pit, end});
886                 }
887
888                 // If we find an InsetArgument that is supposed to provide the TOC caption,
889                 // we'll save it for use later.
890                 InsetArgument const * arginset = nullptr;
891                 for (auto const & table : par.insetList()) {
892                         dit.pos() = table.pos;
893                         table.inset->addToToc(dit, doing_output, utype, backend);
894                         if (InsetArgument const * x = table.inset->asInsetArgument())
895                                 if (x->isTocCaption())
896                                         arginset = x;
897                 }
898
899                 // End custom AddToToc in paragraph layouts
900                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
901                         // execute the closing function
902                         closeAddToTocForParagraph(addtotoc_stack.top().first,
903                                                   addtotoc_stack.top().second, backend);
904                         addtotoc_stack.pop();
905                 }
906
907                 // now the toc entry for the paragraph in the main table of contents
908                 int const toclevel = text().getTocLevel(pit);
909                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
910                         // insert this into the table of contents
911                         docstring tocstring;
912                         int const length = (doing_output && utype == OutputUpdate) ?
913                                 INT_MAX : TOC_ENTRY_LENGTH;
914                         if (arginset) {
915                                 tocstring = par.labelString();
916                                 if (!tocstring.empty())
917                                         tocstring += ' ';
918                                 arginset->text().forOutliner(tocstring, length);
919                         } else
920                                 par.forOutliner(tocstring, length);
921                         dit.pos() = 0;
922                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
923                                                tocstring, doing_output));
924                 }
925
926                 // And now the list of changes.
927                 par.addChangesToToc(dit, buffer(), doing_output, backend);
928         }
929 }
930
931
932 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
933                                              DocIterator const & dit,
934                                              bool output_active,
935                                              TocBackend & backend) const
936 {
937         Paragraph const & par = paragraphs()[pit];
938         TocBuilder & b = backend.builder(par.layout().tocType());
939         docstring const label = par.labelString();
940         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
941         return text().lastInSequence(pit);
942 }
943
944
945 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
946                                           TocBackend & backend) const
947 {
948         Paragraph const & par = paragraphs()[start];
949         TocBuilder & b = backend.builder(par.layout().tocType());
950         if (par.layout().isTocCaption()) {
951                 docstring str;
952                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
953                 b.argumentItem(str);
954         }
955         b.pop();
956 }
957
958
959 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
960 {
961         if (buffer().isClean())
962                 return Inset::notifyCursorLeaves(old, cur);
963
964         // find text inset in old cursor
965         Cursor insetCur = old;
966         int scriptSlice = insetCur.find(this);
967         // we can try to continue here. returning true means
968         // the cursor is "now" invalid. which it was.
969         LASSERT(scriptSlice != -1, return true);
970         insetCur.cutOff(scriptSlice);
971         LASSERT(&insetCur.inset() == this, return true);
972
973         // update the old paragraph's words
974         insetCur.paragraph().updateWords();
975
976         return Inset::notifyCursorLeaves(old, cur);
977 }
978
979
980 bool InsetText::completionSupported(Cursor const & cur) const
981 {
982         //LASSERT(&cur.bv().cursor().inset() == this, return false);
983         return text_.completionSupported(cur);
984 }
985
986
987 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
988 {
989         return completionSupported(cur);
990 }
991
992
993 bool InsetText::automaticInlineCompletion() const
994 {
995         return lyxrc.completion_inline_text;
996 }
997
998
999 bool InsetText::automaticPopupCompletion() const
1000 {
1001         return lyxrc.completion_popup_text;
1002 }
1003
1004
1005 bool InsetText::showCompletionCursor() const
1006 {
1007         return lyxrc.completion_cursor_text;
1008 }
1009
1010
1011 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1012 {
1013         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1014 }
1015
1016
1017 docstring InsetText::completionPrefix(Cursor const & cur) const
1018 {
1019         if (!completionSupported(cur))
1020                 return docstring();
1021         return text_.completionPrefix(cur);
1022 }
1023
1024
1025 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1026         bool finished)
1027 {
1028         if (!completionSupported(cur))
1029                 return false;
1030
1031         return text_.insertCompletion(cur, s, finished);
1032 }
1033
1034
1035 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1036         Dimension & dim) const
1037 {
1038         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1039         tm.completionPosAndDim(cur, x, y, dim);
1040 }
1041
1042
1043 string InsetText::contextMenu(BufferView const &, int, int) const
1044 {
1045         string context_menu = contextMenuName();
1046         if (context_menu != InsetText::contextMenuName())
1047                 context_menu += ";" + InsetText::contextMenuName();
1048         return context_menu;
1049 }
1050
1051
1052 string InsetText::contextMenuName() const
1053 {
1054         return "context-edit";
1055 }
1056
1057
1058 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1059 {
1060         OutputParams rp(&buffer().params().encoding());
1061         rp.for_tooltip = true;
1062         odocstringstream oss;
1063         oss << prefix;
1064
1065         ParagraphList::const_iterator beg = paragraphs().begin();
1066         ParagraphList::const_iterator end = paragraphs().end();
1067         ParagraphList::const_iterator it = beg;
1068         bool ref_printed = false;
1069
1070         for (; it != end; ++it) {
1071                 if (it != beg)
1072                         oss << '\n';
1073                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1074                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1075                         break;
1076         }
1077         docstring str = oss.str();
1078         support::truncateWithEllipsis(str, len);
1079         return str;
1080 }
1081
1082
1083 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1084 {
1085         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1086 }
1087
1088
1089 bool InsetText::needsCProtection() const
1090 {
1091         if (!getLayout().needsCProtect())
1092                 return false;
1093
1094         // Environments need cprotection regardless the content
1095         if (getLayout().latextype() == InsetLayout::ENVIRONMENT)
1096                 return true;
1097
1098         // Commands need cprotection if they contain specific chars
1099         int const nchars_escape = 9;
1100         static char_type const chars_escape[nchars_escape] = {
1101                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1102
1103         ParagraphList const & pars = paragraphs();
1104         pit_type pend = paragraphs().size();
1105
1106         for (pit_type pit = 0; pit != pend; ++pit) {
1107                 Paragraph const & par = pars[pit];
1108                 if (par.needsCProtection())
1109                         return true;
1110                 docstring const pars = par.asString();
1111                 for (int k = 0; k < nchars_escape; k++) {
1112                         if (contains(pars, chars_escape[k]))
1113                                 return true;
1114                 }
1115         }
1116         return false;
1117 }
1118
1119 } // namespace lyx