]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
Move labels and insets out of moving arguments
[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.dim();
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.isNeedMBoxProtect())
503                 ++rp.inulemcmd;
504         if (!il.passThruChars().empty())
505                 rp.pass_thru_chars += il.passThruChars();
506         rp.par_begin = 0;
507         rp.par_end = paragraphs().size();
508
509         // Output the contents of the inset
510         latexParagraphs(buffer(), text_, os, rp);
511         runparams.encoding = rp.encoding;
512         // Pass the post_macros upstream
513         runparams.post_macro = rp.post_macro;
514
515         if (!il.rightdelim().empty())
516                 os << il.rightdelim();
517
518         if (!il.latexname().empty()) {
519                 if (il.latextype() == InsetLayout::COMMAND) {
520                         os << "}";
521                         if (!il.postcommandargs().empty())
522                                 getArgs(os, runparams, true);
523                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
524                         // A comment environment doesn't need a % before \n\end
525                         if (il.isDisplay() || runparams.inComment)
526                                 os << breakln;
527                         else
528                                 os << safebreakln;
529                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
530                         if (!il.isDisplay())
531                                 os.protectSpace(true);
532                 }
533         }
534         if (il.forceOwnlines())
535                 os << breakln;
536 }
537
538
539 int InsetText::plaintext(odocstringstream & os,
540         OutputParams const & runparams, size_t max_length) const
541 {
542         ParagraphList::const_iterator beg = paragraphs().begin();
543         ParagraphList::const_iterator end = paragraphs().end();
544         ParagraphList::const_iterator it = beg;
545         bool ref_printed = false;
546         int len = 0;
547         for (; it != end; ++it) {
548                 if (it != beg) {
549                         os << '\n';
550                         if (runparams.linelen > 0)
551                                 os << '\n';
552                 }
553                 odocstringstream oss;
554                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
555                 docstring const str = oss.str();
556                 os << str;
557                 // FIXME: len is not computed fully correctly; in principle,
558                 // we have to count the characters after the last '\n'
559                 len = str.size();
560                 if (os.str().size() >= max_length)
561                         break;
562         }
563
564         return len;
565 }
566
567
568 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
569 {
570         ParagraphList::const_iterator const beg = paragraphs().begin();
571
572         if (!undefined())
573                 sgml::openTag(os, getLayout().latexname(),
574                               beg->getID(buffer(), runparams) + getLayout().latexparam());
575
576         docbookParagraphs(text_, buffer(), os, runparams);
577
578         if (!undefined())
579                 sgml::closeTag(os, getLayout().latexname());
580
581         return 0;
582 }
583
584
585 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
586 {
587         return insetAsXHTML(xs, runparams, WriteEverything);
588 }
589
590
591 // FIXME XHTML
592 // There are cases where we may need to close open fonts and such
593 // and then re-open them when we are done. This would be the case, e.g.,
594 // if we were otherwise about to write:
595 //              <em>word <div class='foot'>footnote text.</div> emph</em>
596 // The problem isn't so much that the footnote text will get emphasized:
597 // we can handle that with CSS. The problem is that this is invalid XHTML.
598 // One solution would be to make the footnote <span>, but the problem is
599 // completely general, and so we'd have to make absolutely everything into
600 // span. What I think will work is to check if we're about to write "div" and,
601 // if so, try to close fonts, etc.
602 // There are probably limits to how well we can do here, though, and we will
603 // have to rely upon users not putting footnotes inside noun-type insets.
604 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
605                                   XHTMLOptions opts) const
606 {
607         // we will always want to output all our paragraphs when we are
608         // called this way.
609         OutputParams runparams = rp;
610         runparams.par_begin = 0;
611         runparams.par_end = text().paragraphs().size();
612
613         if (undefined()) {
614                 xs.startDivision(false);
615                 xhtmlParagraphs(text_, buffer(), xs, runparams);
616                 xs.endDivision();
617                 return docstring();
618         }
619
620         InsetLayout const & il = getLayout();
621         if (opts & WriteOuterTag)
622                 xs << html::StartTag(il.htmltag(), il.htmlattr());
623
624         if ((opts & WriteLabel) && !il.counter().empty()) {
625                 BufferParams const & bp = buffer().masterBuffer()->params();
626                 Counters & cntrs = bp.documentClass().counters();
627                 cntrs.step(il.counter(), OutputUpdate);
628                 // FIXME: translate to paragraph language
629                 if (!il.htmllabel().empty()) {
630                         docstring const lbl =
631                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
632                         // FIXME is this check necessary?
633                         if (!lbl.empty()) {
634                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
635                                 xs << lbl;
636                                 xs << html::EndTag(il.htmllabeltag());
637                         }
638                 }
639         }
640
641         if (opts & WriteInnerTag)
642                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
643
644         // we will eventually lose information about the containing inset
645         if (!allowMultiPar() || opts == JustText)
646                 runparams.html_make_pars = false;
647         if (il.isPassThru())
648                 runparams.pass_thru = true;
649
650         xs.startDivision(false);
651         xhtmlParagraphs(text_, buffer(), xs, runparams);
652         xs.endDivision();
653
654         if (opts & WriteInnerTag)
655                 xs << html::EndTag(il.htmlinnertag());
656
657         if (opts & WriteOuterTag)
658                 xs << html::EndTag(il.htmltag());
659
660         return docstring();
661 }
662
663
664 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
665                         bool const post) const
666 {
667         OutputParams runparams = runparams_in;
668         runparams.local_font =
669                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
670         if (isPassThru())
671                 runparams.pass_thru = true;
672         if (post)
673                 latexArgInsetsForParent(paragraphs(), os, runparams,
674                                         getLayout().postcommandargs(), "post:");
675         else
676                 latexArgInsetsForParent(paragraphs(), os, runparams,
677                                         getLayout().latexargs());
678 }
679
680
681 void InsetText::cursorPos(BufferView const & bv,
682                 CursorSlice const & sl, bool boundary, int & x, int & y) const
683 {
684         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
685         y = bv.textMetrics(&text_).cursorY(sl, boundary);
686 }
687
688
689 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
690 {
691         clear();
692         Paragraph & first = paragraphs().front();
693         for (unsigned int i = 0; i < data.length(); ++i)
694                 first.insertChar(i, data[i], font, trackChanges);
695 }
696
697
698 void InsetText::setDrawFrame(bool flag)
699 {
700         drawFrame_ = flag;
701 }
702
703
704 ColorCode InsetText::frameColor() const
705 {
706         return frame_color_;
707 }
708
709
710 void InsetText::setFrameColor(ColorCode col)
711 {
712         frame_color_ = col;
713 }
714
715
716 void InsetText::appendParagraphs(ParagraphList & plist)
717 {
718         // There is little we can do here to keep track of changes.
719         // As of 2006/10/20, appendParagraphs is used exclusively by
720         // LyXTabular::setMultiColumn. In this context, the paragraph break
721         // is lost irreversibly and the appended text doesn't really change
722
723         ParagraphList & pl = paragraphs();
724
725         ParagraphList::iterator pit = plist.begin();
726         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
727         ++pit;
728         mergeParagraph(buffer().params(), pl,
729                        distance(pl.begin(), ins) - 1);
730
731         for_each(pit, plist.end(),
732                  bind(&ParagraphList::push_back, ref(pl), _1));
733 }
734
735
736 void InsetText::addPreview(DocIterator const & text_inset_pos,
737         PreviewLoader & loader) const
738 {
739         ParagraphList::const_iterator pit = paragraphs().begin();
740         ParagraphList::const_iterator pend = paragraphs().end();
741         int pidx = 0;
742
743         DocIterator inset_pos = text_inset_pos;
744         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
745
746         for (; pit != pend; ++pit, ++pidx) {
747                 InsetList::const_iterator it  = pit->insetList().begin();
748                 InsetList::const_iterator end = pit->insetList().end();
749                 inset_pos.pit() = pidx;
750                 for (; it != end; ++it) {
751                         inset_pos.pos() = it->pos;
752                         it->inset->addPreview(inset_pos, loader);
753                 }
754         }
755 }
756
757
758 ParagraphList const & InsetText::paragraphs() const
759 {
760         return text_.paragraphs();
761 }
762
763
764 ParagraphList & InsetText::paragraphs()
765 {
766         return text_.paragraphs();
767 }
768
769
770 bool InsetText::hasCProtectContent(bool const fragile) const
771 {
772         ParagraphList const & pars = paragraphs();
773         pit_type pend = paragraphs().size();
774         for (pit_type pit = 0; pit != pend; ++pit) {
775                 Paragraph const & par = pars[pit];
776                 if (par.needsCProtection(fragile))
777                         return true;
778         }
779         return false;
780 }
781
782
783 bool InsetText::insetAllowed(InsetCode code) const
784 {
785         switch (code) {
786         // Arguments and (plain) quotes are also allowed in PassThru insets
787         case ARG_CODE:
788         case QUOTE_CODE:
789                 return true;
790         default:
791                 return !isPassThru();
792         }
793 }
794
795
796 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
797 {
798         ParIterator it2 = it;
799         it2.forwardPos();
800         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
801         if (producesOutput()) {
802                 InsetLayout const & il = getLayout();
803                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
804                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
805                 if (save_layouts) {
806                         // LYXERR0("Entering " << name());
807                         cnt.clearLastLayout();
808                         // FIXME cnt.saveLastCounter()?
809                 }
810                 buffer().updateBuffer(it2, utype);
811                 if (save_layouts) {
812                         // LYXERR0("Exiting " << name());
813                         cnt.restoreLastLayout();
814                         // FIXME cnt.restoreLastCounter()?
815                 }
816         } else {
817                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
818                 // Note that we do not need to call:
819                 //      tclass.counters().clearLastLayout()
820                 // since we are saving and restoring the existing counters, etc.
821                 Counters savecnt = tclass.counters();
822                 tclass.counters().reset();
823                 // we need float information even in note insets (#9760)
824                 tclass.counters().current_float(savecnt.current_float());
825                 tclass.counters().isSubfloat(savecnt.isSubfloat());
826                 buffer().updateBuffer(it2, utype);
827                 tclass.counters() = move(savecnt);
828         }
829 }
830
831
832 void InsetText::toString(odocstream & os) const
833 {
834         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
835 }
836
837
838 void InsetText::forOutliner(docstring & os, size_t const maxlen,
839                                                         bool const shorten) const
840 {
841         if (!getLayout().isInToc())
842                 return;
843         text().forOutliner(os, maxlen, shorten);
844 }
845
846
847 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
848                                                  UpdateType utype, TocBackend & backend) const
849 {
850         DocIterator dit = cdit;
851         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
852         iterateForToc(dit, output_active, utype, backend);
853 }
854
855
856 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
857                                                           UpdateType utype, TocBackend & backend) const
858 {
859         DocIterator dit = cdit;
860         // This also ensures that any document has a table of contents
861         shared_ptr<Toc> toc = backend.toc("tableofcontents");
862
863         BufferParams const & bufparams = buffer_->params();
864         int const min_toclevel = bufparams.documentClass().min_toclevel();
865         // we really should have done this before we got here, but it
866         // can't hurt too much to do it again
867         bool const doing_output = output_active && producesOutput();
868
869         // For each paragraph,
870         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
871         //   paragraphs as needed.
872         // * Traverse its insets and let them add their toc items
873         // * Compute the main table of contents (this is hardcoded)
874         // * Add the list of changes
875         ParagraphList const & pars = paragraphs();
876         pit_type pend = paragraphs().size();
877         // Record pairs {start,end} of where a toc item was opened for a paragraph
878         // and where it must be closed
879         stack<pair<pit_type, pit_type>> addtotoc_stack;
880
881         for (pit_type pit = 0; pit != pend; ++pit) {
882                 Paragraph const & par = pars[pit];
883                 dit.pit() = pit;
884                 dit.pos() = 0;
885
886                 // Custom AddToToc in paragraph layouts (i.e. theorems)
887                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
888                         pit_type end =
889                                 openAddToTocForParagraph(pit, dit, output_active, backend);
890                         addtotoc_stack.push({pit, end});
891                 }
892
893                 // If we find an InsetArgument that is supposed to provide the TOC caption,
894                 // we'll save it for use later.
895                 InsetArgument const * arginset = nullptr;
896                 for (auto const & table : par.insetList()) {
897                         dit.pos() = table.pos;
898                         table.inset->addToToc(dit, doing_output, utype, backend);
899                         if (InsetArgument const * x = table.inset->asInsetArgument())
900                                 if (x->isTocCaption())
901                                         arginset = x;
902                 }
903
904                 // End custom AddToToc in paragraph layouts
905                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
906                         // execute the closing function
907                         closeAddToTocForParagraph(addtotoc_stack.top().first,
908                                                   addtotoc_stack.top().second, backend);
909                         addtotoc_stack.pop();
910                 }
911
912                 // now the toc entry for the paragraph in the main table of contents
913                 int const toclevel = text().getTocLevel(pit);
914                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
915                         // insert this into the table of contents
916                         docstring tocstring;
917                         int const length = (doing_output && utype == OutputUpdate) ?
918                                 INT_MAX : TOC_ENTRY_LENGTH;
919                         if (arginset) {
920                                 tocstring = par.labelString();
921                                 if (!tocstring.empty())
922                                         tocstring += ' ';
923                                 arginset->text().forOutliner(tocstring, length);
924                         } else
925                                 par.forOutliner(tocstring, length);
926                         dit.pos() = 0;
927                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
928                                                tocstring, doing_output));
929                 }
930
931                 // And now the list of changes.
932                 par.addChangesToToc(dit, buffer(), doing_output, backend);
933         }
934 }
935
936
937 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
938                                              DocIterator const & dit,
939                                              bool output_active,
940                                              TocBackend & backend) const
941 {
942         Paragraph const & par = paragraphs()[pit];
943         TocBuilder & b = backend.builder(par.layout().tocType());
944         docstring const label = par.labelString();
945         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
946         return text().lastInSequence(pit);
947 }
948
949
950 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
951                                           TocBackend & backend) const
952 {
953         Paragraph const & par = paragraphs()[start];
954         TocBuilder & b = backend.builder(par.layout().tocType());
955         if (par.layout().isTocCaption()) {
956                 docstring str;
957                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
958                 b.argumentItem(str);
959         }
960         b.pop();
961 }
962
963
964 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
965 {
966         if (buffer().isClean())
967                 return Inset::notifyCursorLeaves(old, cur);
968
969         // find text inset in old cursor
970         Cursor insetCur = old;
971         int scriptSlice = insetCur.find(this);
972         // we can try to continue here. returning true means
973         // the cursor is "now" invalid. which it was.
974         LASSERT(scriptSlice != -1, return true);
975         insetCur.cutOff(scriptSlice);
976         LASSERT(&insetCur.inset() == this, return true);
977
978         // update the old paragraph's words
979         insetCur.paragraph().updateWords();
980
981         return Inset::notifyCursorLeaves(old, cur);
982 }
983
984
985 bool InsetText::completionSupported(Cursor const & cur) const
986 {
987         //LASSERT(&cur.bv().cursor().inset() == this, return false);
988         return text_.completionSupported(cur);
989 }
990
991
992 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
993 {
994         return completionSupported(cur);
995 }
996
997
998 bool InsetText::automaticInlineCompletion() const
999 {
1000         return lyxrc.completion_inline_text;
1001 }
1002
1003
1004 bool InsetText::automaticPopupCompletion() const
1005 {
1006         return lyxrc.completion_popup_text;
1007 }
1008
1009
1010 bool InsetText::showCompletionCursor() const
1011 {
1012         return lyxrc.completion_cursor_text;
1013 }
1014
1015
1016 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1017 {
1018         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1019 }
1020
1021
1022 docstring InsetText::completionPrefix(Cursor const & cur) const
1023 {
1024         if (!completionSupported(cur))
1025                 return docstring();
1026         return text_.completionPrefix(cur);
1027 }
1028
1029
1030 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1031         bool finished)
1032 {
1033         if (!completionSupported(cur))
1034                 return false;
1035
1036         return text_.insertCompletion(cur, s, finished);
1037 }
1038
1039
1040 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1041         Dimension & dim) const
1042 {
1043         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1044         tm.completionPosAndDim(cur, x, y, dim);
1045 }
1046
1047
1048 string InsetText::contextMenu(BufferView const &, int, int) const
1049 {
1050         string context_menu = contextMenuName();
1051         if (context_menu != InsetText::contextMenuName())
1052                 context_menu += ";" + InsetText::contextMenuName();
1053         return context_menu;
1054 }
1055
1056
1057 string InsetText::contextMenuName() const
1058 {
1059         return "context-edit";
1060 }
1061
1062
1063 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
1064 {
1065         OutputParams rp(&buffer().params().encoding());
1066         rp.for_tooltip = true;
1067         odocstringstream oss;
1068         oss << prefix;
1069
1070         ParagraphList::const_iterator beg = paragraphs().begin();
1071         ParagraphList::const_iterator end = paragraphs().end();
1072         ParagraphList::const_iterator it = beg;
1073         bool ref_printed = false;
1074
1075         for (; it != end; ++it) {
1076                 if (it != beg)
1077                         oss << '\n';
1078                 if ((*it).isRTL(buffer().params()))
1079                         oss << "<div dir=\"rtl\">";
1080                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1081                 if ((*it).isRTL(buffer().params()))
1082                         oss << "</div>";
1083                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1084                         break;
1085         }
1086         docstring str = oss.str();
1087         support::truncateWithEllipsis(str, len);
1088         return str;
1089 }
1090
1091
1092 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1093 {
1094         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1095 }
1096
1097
1098 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1099 {
1100         // Nested cprotect content needs \cprotect
1101         // on each level
1102         if (producesOutput() && hasCProtectContent(fragile))
1103                 return true;
1104
1105         // Environments generally need cprotection in fragile context
1106         if (fragile && getLayout().latextype() == InsetLayout::ENVIRONMENT)
1107                 return true;
1108
1109         if (!getLayout().needsCProtect())
1110                 return false;
1111
1112         // Environments and "no latex" types (e.g., knitr chunks)
1113         // need cprotection regardless the content
1114         if (!maintext && getLayout().latextype() != InsetLayout::COMMAND)
1115                 return true;
1116
1117         // If the inset does not produce output (e.g. Note or Branch),
1118         // we can ignore the contained paragraphs
1119         if (!producesOutput())
1120                 return false;
1121
1122         // Commands need cprotection if they contain specific chars
1123         int const nchars_escape = 9;
1124         static char_type const chars_escape[nchars_escape] = {
1125                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1126
1127         ParagraphList const & pars = paragraphs();
1128         pit_type pend = paragraphs().size();
1129
1130         for (pit_type pit = 0; pit != pend; ++pit) {
1131                 Paragraph const & par = pars[pit];
1132                 if (par.needsCProtection(fragile))
1133                         return true;
1134                 docstring const pars = par.asString();
1135                 for (int k = 0; k < nchars_escape; k++) {
1136                         if (contains(pars, chars_escape[k]))
1137                                 return true;
1138                 }
1139         }
1140         return false;
1141 }
1142
1143 } // namespace lyx