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