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