]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Keep dialog connected to cross-ref inset after Apply.
[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 "InsetLayout.h"
14 #include "InsetText.h"
15
16 #include "insets/InsetArgument.h"
17 #include "insets/InsetLayout.h"
18
19 #include "buffer_funcs.h"
20 #include "Buffer.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "CompletionList.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "InsetList.h"
32 #include "Intl.h"
33 #include "Language.h"
34 #include "Layout.h"
35 #include "LaTeXFeatures.h"
36 #include "Lexer.h"
37 #include "lyxfind.h"
38 #include "LyXRC.h"
39 #include "MetricsInfo.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_plaintext.h"
43 #include "output_xhtml.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TexRow.h"
48 #include "texstream.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53 #include "TocBuilder.h"
54
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
57
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/Changer.h"
64
65 #include <algorithm>
66 #include <stack>
67
68
69 using namespace std;
70 using namespace lyx::support;
71
72
73 namespace lyx {
74
75 using graphics::PreviewLoader;
76
77
78 /////////////////////////////////////////////////////////////////////
79
80 InsetText::InsetText(Buffer * buf, UsePlain type)
81         : Inset(buf), drawFrame_(false), is_changed_(false), intitle_context_(false),
82           frame_color_(Color_insetframe),
83         text_(this, type == DefaultLayout)
84 {
85 }
86
87
88 InsetText::InsetText(InsetText const & in)
89         : Inset(in), drawFrame_(in.drawFrame_), is_changed_(in.is_changed_),
90           intitle_context_(false), frame_color_(in.frame_color_),
91           text_(this, in.text_)
92 {
93 }
94
95
96 void InsetText::setBuffer(Buffer & buf)
97 {
98         ParagraphList::iterator end = paragraphs().end();
99         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100                 it->setInsetBuffers(buf);
101         Inset::setBuffer(buf);
102 }
103
104
105 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
106 {
107         text_.setMacrocontextPosition(pos);
108
109         ParagraphList::const_iterator pit = paragraphs().begin();
110         ParagraphList::const_iterator pend = paragraphs().end();
111         for (; pit != pend; ++pit) {
112                 InsetList::const_iterator iit = pit->insetList().begin();
113                 InsetList::const_iterator end = pit->insetList().end();
114                 for (; iit != end; ++iit) {
115                         if (InsetText * txt = iit->inset->asInsetText()) {
116                                 DocIterator ppos(pos);
117                                 ppos.push_back(CursorSlice(*txt));
118                                 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
119                         }
120                 }
121         }
122 }
123
124
125 void InsetText::clear()
126 {
127         ParagraphList & pars = paragraphs();
128         LBUFERR(!pars.empty());
129
130         // This is a gross hack...
131         Layout const & old_layout = pars.begin()->layout();
132
133         pars.clear();
134         pars.push_back(Paragraph());
135         pars.begin()->setInsetOwner(this);
136         pars.begin()->setLayout(old_layout);
137 }
138
139
140 Dimension const InsetText::dimensionHelper(BufferView const & bv) const
141 {
142         TextMetrics const & tm = bv.textMetrics(&text_);
143         Dimension dim = tm.dim();
144         dim.wid += leftOffset(&bv) + rightOffset(&bv);
145         dim.des += bottomOffset(&bv);
146         dim.asc += topOffset(&bv);
147         return dim;
148 }
149
150
151 void InsetText::write(ostream & os) const
152 {
153         os << "Text\n";
154         text_.write(os);
155 }
156
157
158 void InsetText::read(Lexer & lex)
159 {
160         clear();
161
162         // delete the initial paragraph
163         Paragraph oldpar = *paragraphs().begin();
164         paragraphs().clear();
165         ErrorList errorList;
166         lex.setContext("InsetText::read");
167         bool res = text_.read(lex, errorList, this);
168
169         if (!res)
170                 lex.printError("Missing \\end_inset at this point. ");
171
172         // sanity check
173         // ensure we have at least one paragraph.
174         if (paragraphs().empty())
175                 paragraphs().push_back(oldpar);
176         // Force default font, if so requested
177         // This avoids paragraphs in buffer language that would have a
178         // foreign language after a document language change, and it ensures
179         // that all new text in ERT and similar gets the "latex" language,
180         // since new text inherits the language from the last position of the
181         // existing text.  As a side effect this makes us also robust against
182         // bugs in LyX that might lead to font changes in ERT in .lyx files.
183         fixParagraphsFont();
184 }
185
186
187 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
188 {
189         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
190
191         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
192
193         int const horiz_offset = leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
194
195         // Hand font through to contained lyxtext:
196         tm.font_.fontInfo() = mi.base.font;
197         mi.base.textwidth -= horiz_offset;
198
199         // This can happen when a layout has a left and right margin,
200         // and the view is made very narrow. We can't do better than
201         // to draw it partly out of view (bug 5890).
202         if (mi.base.textwidth < 1)
203                 mi.base.textwidth = 1;
204
205         if (hasFixedWidth())
206                 tm.metrics(mi, dim, mi.base.textwidth);
207         else
208                 tm.metrics(mi, dim);
209         mi.base.textwidth += horiz_offset;
210         dim.asc += topOffset(mi.base.bv);
211         dim.des += bottomOffset(mi.base.bv);
212         dim.wid += horiz_offset;
213 }
214
215
216 void InsetText::draw(PainterInfo & pi, int x, int y) const
217 {
218         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
219
220         int const horiz_offset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
221         int const w = tm.width() + (horiz_offset - horiz_offset / 2);
222         int const yframe = y - topOffset(pi.base.bv) - tm.ascent();
223         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
224         int const xframe = x + leftOffset(pi.base.bv) / 2;
225         bool change_drawn = false;
226         if (pi.full_repaint)
227                         pi.pain.fillRectangle(xframe, yframe, w, h,
228                                 pi.backgroundColor(this));
229
230         {
231                 Changer dummy = changeVar(pi.background_color,
232                                             pi.backgroundColor(this, false));
233                 // The change tracking cue must not be inherited
234                 Changer dummy2 = changeVar(pi.change, Change());
235                 tm.draw(pi, x + leftOffset(pi.base.bv), y);
236         }
237
238         if (drawFrame_) {
239                 // Change color of the frame in tracked changes, like for tabulars.
240                 // Only do so if the color is not custom. But do so even if RowPainter
241                 // handles the strike-through already.
242                 Color c;
243                 if (pi.change.changed()
244                     // Originally, these are the colors with role Text, from role() in
245                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
246                     // types, and also maybe it need not match in the future.
247                     && (frameColor() == Color_foreground
248                         || frameColor() == Color_cursor
249                         || frameColor() == Color_preview
250                         || frameColor() == Color_tabularline
251                         || frameColor() == Color_previewframe)) {
252                         c = pi.change.color();
253                         change_drawn = true;
254                 } else
255                         c = frameColor();
256                 pi.pain.rectangle(xframe, yframe, w, h, c);
257         }
258
259         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change.deleted()))
260                 // Do not draw the change tracking cue if already done by RowPainter and
261                 // do not draw the cue for INSERTED if the information is already in the
262                 // color of the frame
263                 pi.change.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
264 }
265
266
267 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
268 {
269         pit_type const pit = front ? 0 : paragraphs().size() - 1;
270         pos_type pos = front ? 0 : paragraphs().back().size();
271
272         // if visual information is not to be ignored, move to extreme right/left
273         if (entry_from != ENTRY_DIRECTION_IGNORE) {
274                 Cursor temp_cur = cur;
275                 temp_cur.pit() = pit;
276                 temp_cur.pos() = pos;
277                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
278                 pos = temp_cur.pos();
279         }
280
281         cur.top().setPitPos(pit, pos);
282         cur.setCurrentFont();
283         cur.finishUndo();
284 }
285
286
287 Inset * InsetText::editXY(Cursor & cur, int x, int y)
288 {
289         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
290 }
291
292
293 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
294 {
295         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
296
297 #if 0
298         // See bug #9042, for instance.
299         if (isPassThru()) {
300                 // Force any new text to latex_language FIXME: This
301                 // should only be necessary in constructor, but new
302                 // paragraphs that are created by pressing enter at
303                 // the start of an existing paragraph get the buffer
304                 // language and not latex_language, so we take this
305                 // brute force approach.
306                 cur.current_font.setLanguage(latex_language);
307                 cur.real_current_font.setLanguage(latex_language);
308         }
309 #endif
310
311         switch (cmd.action()) {
312         case LFUN_PASTE:
313         case LFUN_CLIPBOARD_PASTE:
314         case LFUN_SELECTION_PASTE:
315         case LFUN_PRIMARY_SELECTION_PASTE:
316                 text_.dispatch(cur, cmd);
317                 // If we we can only store plain text, we must reset all
318                 // attributes.
319                 // FIXME: Change only the pasted paragraphs
320                 fixParagraphsFont();
321                 break;
322
323         case LFUN_INSET_SPLIT:
324         case LFUN_INSET_DISSOLVE: {
325                 bool const main_inset = text_.isMainText();
326                 bool const target_inset = cmd.argument().empty()
327                         || cmd.getArg(0) == insetName(lyxCode());
328
329                 if (!main_inset && target_inset) {
330                         // Text::dissolveInset assumes that the cursor
331                         // is inside the Inset.
332                         if (&cur.inset() != this)
333                                 cur.pushBackward(*this);
334                         cur.beginUndoGroup();
335                         text_.dispatch(cur, cmd);
336                         cur.endUndoGroup();
337                 } else
338                         cur.undispatched();
339                 break;
340         }
341
342         default:
343                 text_.dispatch(cur, cmd);
344         }
345
346         if (!cur.result().dispatched())
347                 Inset::doDispatch(cur, cmd);
348 }
349
350
351 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
352         FuncStatus & status) const
353 {
354         switch (cmd.action()) {
355         case LFUN_INSET_SPLIT:
356         case LFUN_INSET_DISSOLVE: {
357                 bool const main_inset = text_.isMainText();
358                 bool const target_inset = cmd.argument().empty()
359                         || cmd.getArg(0) == insetName(lyxCode());
360
361                 if (target_inset)
362                         status.setEnabled(!main_inset);
363                 return target_inset;
364         }
365
366         case LFUN_ARGUMENT_INSERT: {
367                 string const arg = cmd.getArg(0);
368                 if (arg.empty()) {
369                         status.setEnabled(false);
370                         return true;
371                 }
372                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
373                         return text_.getStatus(cur, cmd, status);
374
375                 Layout::LaTeXArgMap args = getLayout().args();
376                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
377                 if (lait != args.end()) {
378                         status.setEnabled(true);
379                         for (Paragraph const & par : paragraphs())
380                                 for (auto const & table : par.insetList())
381                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
382                                                 if (ins->name() == arg) {
383                                                         // we have this already
384                                                         status.setEnabled(false);
385                                                         return true;
386                                                 }
387                 } else
388                         status.setEnabled(false);
389                 return true;
390         }
391
392         default:
393                 // Dispatch only to text_ if the cursor is inside
394                 // the text_. It is not for context menus (bug 5797).
395                 bool ret = false;
396                 if (cur.text() == &text_)
397                         ret = text_.getStatus(cur, cmd, status);
398
399                 if (!ret)
400                         ret = Inset::getStatus(cur, cmd, status);
401                 return ret;
402         }
403 }
404
405
406 void InsetText::fixParagraphsFont()
407 {
408         Font font(inherit_font, buffer().params().language);
409         font.setLanguage(latex_language);
410         ParagraphList::iterator par = paragraphs().begin();
411         ParagraphList::iterator const end = paragraphs().end();
412         while (par != end) {
413                 if (par->isPassThru())
414                         par->resetFonts(font);
415                 if (!par->allowParagraphCustomization())
416                         par->params().clear();
417                 ++par;
418         }
419 }
420
421
422 // bool InsetText::isChanged() const
423 // {
424 //      ParagraphList::const_iterator pit = paragraphs().begin();
425 //      ParagraphList::const_iterator end = paragraphs().end();
426 //      for (; pit != end; ++pit) {
427 //              if (pit->isChanged())
428 //                      return true;
429 //      }
430 //      return false;
431 // }
432
433
434 void InsetText::setChange(Change const & change)
435 {
436         ParagraphList::iterator pit = paragraphs().begin();
437         ParagraphList::iterator end = paragraphs().end();
438         for (; pit != end; ++pit) {
439                 pit->setChange(change);
440         }
441 }
442
443
444 void InsetText::acceptChanges()
445 {
446         text_.acceptChanges();
447 }
448
449
450 void InsetText::rejectChanges()
451 {
452         text_.rejectChanges();
453 }
454
455
456 void InsetText::validate(LaTeXFeatures & features) const
457 {
458         features.useInsetLayout(getLayout());
459         for (Paragraph const & p : paragraphs())
460                 p.validate(features);
461 }
462
463
464 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
465 {
466         // This implements the standard way of handling the LaTeX
467         // output of a text inset, either a command or an
468         // environment. Standard collapsible insets should not
469         // redefine this, non-standard ones may call this.
470         InsetLayout const & il = getLayout();
471         if (il.forceOwnlines())
472                 os << breakln;
473         bool needendgroup = false;
474         if (!il.latexname().empty()) {
475                 if (il.latextype() == InsetLaTeXType::COMMAND) {
476                         // FIXME UNICODE
477                         // FIXME \protect should only be used for fragile
478                         //    commands, but we do not provide this information yet.
479                         if (hasCProtectContent(runparams.moving_arg)) {
480                                 if (contains(runparams.active_chars, '^')) {
481                                         // cprotect relies on ^ being on catcode 7
482                                         os << "\\begingroup\\catcode`\\^=7";
483                                         needendgroup = true;
484                                 }
485                                 os << "\\cprotect";
486                         } else if (runparams.moving_arg)
487                                 os << "\\protect";
488                         os << '\\' << from_utf8(il.latexname());
489                         if (!il.latexargs().empty())
490                                 getArgs(os, runparams);
491                         if (!il.latexparam().empty())
492                                 os << from_utf8(il.latexparam());
493                         os << '{';
494                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
495                         if (il.isDisplay())
496                                 os << breakln;
497                         else
498                                 os << safebreakln;
499                         if (runparams.lastid != -1)
500                                 os.texrow().start(runparams.lastid,
501                                                   runparams.lastpos);
502                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
503                         if (!il.latexargs().empty())
504                                 getArgs(os, runparams);
505                         if (!il.latexparam().empty())
506                                 os << from_utf8(il.latexparam());
507                         os << '\n';
508                 }
509         } else {
510                 if (!il.latexargs().empty())
511                         getArgs(os, runparams);
512                 if (!il.latexparam().empty())
513                         os << from_utf8(il.latexparam());
514         }
515
516         if (!il.leftdelim().empty())
517                 os << il.leftdelim();
518
519         OutputParams rp = runparams;
520         if (isPassThru())
521                 rp.pass_thru = true;
522         if (il.isNeedProtect())
523                 rp.moving_arg = true;
524         if (il.isNeedMBoxProtect())
525                 ++rp.inulemcmd;
526         if (!il.passThruChars().empty())
527                 rp.pass_thru_chars += il.passThruChars();
528         if (!il.newlineCmd().empty())
529                 rp.newlinecmd = il.newlineCmd();
530         rp.par_begin = 0;
531         rp.par_end = paragraphs().size();
532
533         // Output the contents of the inset
534         latexParagraphs(buffer(), text_, os, rp);
535         runparams.encoding = rp.encoding;
536         // Pass the post_macros upstream
537         runparams.post_macro = rp.post_macro;
538         // These need to be passed upstream as well
539         runparams.need_maketitle = rp.need_maketitle;
540         runparams.have_maketitle = rp.have_maketitle;
541
542         if (!il.rightdelim().empty())
543                 os << il.rightdelim();
544
545         if (!il.latexname().empty()) {
546                 if (il.latextype() == InsetLaTeXType::COMMAND) {
547                         os << "}";
548                         if (!il.postcommandargs().empty())
549                                 getArgs(os, runparams, true);
550                         if (needendgroup)
551                                 os << "\\endgroup";
552                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
553                         // A comment environment doesn't need a % before \n\end
554                         if (il.isDisplay() || runparams.inComment)
555                                 os << breakln;
556                         else
557                                 os << safebreakln;
558                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
559                         if (!il.isDisplay())
560                                 os.protectSpace(true);
561                 }
562         }
563         if (il.forceOwnlines())
564                 os << breakln;
565 }
566
567
568 int InsetText::plaintext(odocstringstream & os,
569         OutputParams const & runparams, size_t max_length) const
570 {
571         ParagraphList::const_iterator beg = paragraphs().begin();
572         ParagraphList::const_iterator end = paragraphs().end();
573         ParagraphList::const_iterator it = beg;
574         bool ref_printed = false;
575         int len = 0;
576         for (; it != end; ++it) {
577                 if (it != beg) {
578                         os << '\n';
579                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
580                                 os << '\n';
581                 }
582                 odocstringstream oss;
583                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
584                 docstring const str = oss.str();
585                 os << str;
586                 // FIXME: len is not computed fully correctly; in principle,
587                 // we have to count the characters after the last '\n'
588                 len = str.size();
589                 if (os.str().size() >= max_length)
590                         break;
591         }
592
593         return len;
594 }
595
596
597
598 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
599 {
600         docbook(xs, rp, WriteEverything);
601 }
602
603
604 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
605 {
606         // we will always want to output all our paragraphs when we are
607         // called this way.
608         OutputParams runparams = rp;
609         runparams.par_begin = 0;
610         runparams.par_end = text().paragraphs().size();
611
612         if (undefined()) {
613                 xs.startDivision(false);
614                 docbookParagraphs(text_, buffer(), xs, runparams);
615                 xs.endDivision();
616                 return;
617         }
618
619         InsetLayout const & il = getLayout();
620
621         // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
622         // else, typically outside the current paragraph).
623         if (!rp.docbook_generate_info && il.docbookininfo() != "never")
624                 return;
625
626         // In some cases, the input parameters must be overridden for outer tags.
627         bool writeOuterTag = opts & WriteOuterTag;
628         if (writeOuterTag) {
629                 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
630                 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
631                         auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
632                         auto parSize = (size_t) par.size();
633                         return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
634                 });
635                 writeOuterTag = !allBibitems;
636         }
637
638         // Detect arguments that should be output before the paragraph.
639         // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
640         // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
641         std::set<InsetArgument const *> prependedArguments;
642         for (auto const & par : paragraphs()) {
643                 for (pos_type i = 0; i < par.size(); ++i) {
644                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
645                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
646                                 if (arg->docbookargumentbeforemaintag())
647                                         prependedArguments.insert(par.getInset(i)->asInsetArgument());
648                         }
649                 }
650         }
651
652         // Start outputting this inset.
653         // - First, wrapper around the inset and its main tag.
654         if (writeOuterTag) {
655                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
656                         xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
657
658                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
659                         docstring attrs = docstring();
660                         if (!il.docbookattr().empty())
661                                 attrs += from_ascii(il.docbookattr());
662                         if (il.docbooktag() == "link")
663                                 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
664                         xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
665                 }
666         }
667
668         // - Think about the arguments.
669         OutputParams np = runparams;
670         np.docbook_in_par = true;
671         for (auto const & arg : prependedArguments)
672                 arg->docbook(xs, np);
673
674         // - Mark the newly generated arguments are not-to-be-generated-again.
675         runparams.docbook_prepended_arguments = std::move(prependedArguments);
676
677         // - Deal with the first item.
678         // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
679         if (writeOuterTag) {
680                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
681                         xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
682
683                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
684                         xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
685         }
686
687         // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
688
689         // With respect to XHTML, paragraphs are still allowed here.
690         if (!allowMultiPar())
691                 runparams.docbook_make_pars = false;
692         if (il.isPassThru())
693                 runparams.pass_thru = true;
694
695         // - Write the main content of the inset.
696         xs.startDivision(false);
697         docbookParagraphs(text_, buffer(), xs, runparams);
698         xs.endDivision();
699
700         // - Close the required tags.
701         if (writeOuterTag) {
702                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
703                         xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
704
705                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
706                         xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
707
708                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
709                         xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
710
711                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
712                         xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
713         }
714 }
715
716
717 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
718 {
719         return insetAsXHTML(xs, runparams, WriteEverything);
720 }
721
722
723 // FIXME XHTML
724 // There are cases where we may need to close open fonts and such
725 // and then re-open them when we are done. This would be the case, e.g.,
726 // if we were otherwise about to write:
727 //              <em>word <div class='foot'>footnote text.</div> emph</em>
728 // The problem isn't so much that the footnote text will get emphasized:
729 // we can handle that with CSS. The problem is that this is invalid XHTML.
730 // One solution would be to make the footnote <span>, but the problem is
731 // completely general, and so we'd have to make absolutely everything into
732 // span. What I think will work is to check if we're about to write "div" and,
733 // if so, try to close fonts, etc.
734 // There are probably limits to how well we can do here, though, and we will
735 // have to rely upon users not putting footnotes inside noun-type insets.
736 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
737                                   XHTMLOptions opts) const
738 {
739         // we will always want to output all our paragraphs when we are
740         // called this way.
741         OutputParams runparams = rp;
742         runparams.par_begin = 0;
743         runparams.par_end = text().paragraphs().size();
744
745         if (undefined()) {
746                 xs.startDivision(false);
747                 xhtmlParagraphs(text_, buffer(), xs, runparams);
748                 xs.endDivision();
749                 return docstring();
750         }
751
752         InsetLayout const & il = getLayout();
753         if (opts & WriteOuterTag)
754                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
755
756         if ((opts & WriteLabel) && !il.counter().empty()) {
757                 BufferParams const & bp = buffer().masterBuffer()->params();
758                 Counters & cntrs = bp.documentClass().counters();
759                 cntrs.step(il.counter(), OutputUpdate);
760                 // FIXME: translate to paragraph language
761                 if (!il.htmllabel().empty()) {
762                         docstring const lbl =
763                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
764                         // FIXME is this check necessary?
765                         if (!lbl.empty()) {
766                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
767                                 xs << lbl;
768                                 xs << xml::EndTag(il.htmllabeltag());
769                         }
770                 }
771         }
772
773         if (opts & WriteInnerTag)
774                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
775
776         // we will eventually lose information about the containing inset
777         if (!allowMultiPar() || opts == JustText)
778                 runparams.html_make_pars = false;
779         if (il.isPassThru())
780                 runparams.pass_thru = true;
781
782         xs.startDivision(false);
783         xhtmlParagraphs(text_, buffer(), xs, runparams);
784         xs.endDivision();
785
786         if (opts & WriteInnerTag)
787                 xs << xml::EndTag(il.htmlinnertag());
788
789         if (opts & WriteOuterTag)
790                 xs << xml::EndTag(il.htmltag());
791
792         return docstring();
793 }
794
795
796 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
797                         bool const post) const
798 {
799         OutputParams runparams = runparams_in;
800         runparams.local_font =
801                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
802         if (isPassThru())
803                 runparams.pass_thru = true;
804         if (post)
805                 latexArgInsetsForParent(paragraphs(), os, runparams,
806                                         getLayout().postcommandargs(), "post:");
807         else
808                 latexArgInsetsForParent(paragraphs(), os, runparams,
809                                         getLayout().latexargs());
810 }
811
812
813 void InsetText::cursorPos(BufferView const & bv,
814                 CursorSlice const & sl, bool boundary, int & x, int & y) const
815 {
816         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
817         y = bv.textMetrics(&text_).cursorY(sl, boundary);
818 }
819
820
821 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
822 {
823         clear();
824         Paragraph & first = paragraphs().front();
825         for (unsigned int i = 0; i < data.length(); ++i)
826                 first.insertChar(i, data[i], font, trackChanges);
827 }
828
829
830 void InsetText::setDrawFrame(bool flag)
831 {
832         drawFrame_ = flag;
833 }
834
835
836 ColorCode InsetText::frameColor() const
837 {
838         return frame_color_;
839 }
840
841
842 void InsetText::setFrameColor(ColorCode col)
843 {
844         frame_color_ = col;
845 }
846
847
848 void InsetText::appendParagraphs(ParagraphList & plist)
849 {
850         // There is little we can do here to keep track of changes.
851         // As of 2006/10/20, appendParagraphs is used exclusively by
852         // LyXTabular::setMultiColumn. In this context, the paragraph break
853         // is lost irreversibly and the appended text doesn't really change
854
855         ParagraphList & pl = paragraphs();
856
857         ParagraphList::iterator pit = plist.begin();
858         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
859         ++pit;
860         mergeParagraph(buffer().params(), pl,
861                        distance(pl.begin(), ins) - 1);
862
863         ParagraphList::iterator const pend = plist.end();
864         for (; pit != pend; ++pit)
865                 pl.push_back(*pit);
866 }
867
868
869 void InsetText::addPreview(DocIterator const & text_inset_pos,
870         PreviewLoader & loader) const
871 {
872         ParagraphList::const_iterator pit = paragraphs().begin();
873         ParagraphList::const_iterator pend = paragraphs().end();
874         int pidx = 0;
875
876         DocIterator inset_pos = text_inset_pos;
877         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
878
879         for (; pit != pend; ++pit, ++pidx) {
880                 InsetList::const_iterator it  = pit->insetList().begin();
881                 InsetList::const_iterator end = pit->insetList().end();
882                 inset_pos.pit() = pidx;
883                 for (; it != end; ++it) {
884                         inset_pos.pos() = it->pos;
885                         it->inset->addPreview(inset_pos, loader);
886                 }
887         }
888 }
889
890
891 ParagraphList const & InsetText::paragraphs() const
892 {
893         return text_.paragraphs();
894 }
895
896
897 ParagraphList & InsetText::paragraphs()
898 {
899         return text_.paragraphs();
900 }
901
902
903 bool InsetText::hasCProtectContent(bool fragile) const
904 {
905         fragile |= getLayout().isNeedProtect();
906         ParagraphList const & pars = paragraphs();
907         pit_type pend = pit_type(paragraphs().size());
908         for (pit_type pit = 0; pit != pend; ++pit) {
909                 Paragraph const & par = pars[size_type(pit)];
910                 if (par.needsCProtection(fragile))
911                         return true;
912         }
913         return false;
914 }
915
916
917 bool InsetText::insetAllowed(InsetCode code) const
918 {
919         switch (code) {
920         // Arguments and (plain) quotes are also allowed in PassThru insets
921         case ARG_CODE:
922         case QUOTE_CODE:
923                 return true;
924         default:
925                 return !isPassThru();
926         }
927 }
928
929
930 bool InsetText::allowSpellCheck() const
931 {
932         return getLayout().spellcheck() && !getLayout().isPassThru();
933 }
934
935
936 bool InsetText::allowMultiPar() const
937 {
938         return getLayout().isMultiPar();
939 }
940
941
942 bool InsetText::forcePlainLayout(idx_type) const
943 {
944         return getLayout().forcePlainLayout();
945 }
946
947
948 bool InsetText::allowParagraphCustomization(idx_type) const
949 {
950         return getLayout().allowParagraphCustomization();
951 }
952
953
954 bool InsetText::forceLocalFontSwitch() const
955 {
956         return getLayout().forceLocalFontSwitch();
957 }
958
959
960 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
961 {
962         ParIterator it2 = it;
963         it2.forwardPos();
964         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
965         if (producesOutput()) {
966                 InsetLayout const & il = getLayout();
967                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
968                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
969                 if (save_layouts) {
970                         // LYXERR0("Entering " << name());
971                         cnt.clearLastLayout();
972                         // FIXME cnt.saveLastCounter()?
973                 }
974                 buffer().updateBuffer(it2, utype, deleted);
975                 if (save_layouts) {
976                         // LYXERR0("Exiting " << name());
977                         cnt.restoreLastLayout();
978                         // FIXME cnt.restoreLastCounter()?
979                 }
980                 // Record in this inset is embedded in a title layout
981                 // This is needed to decide when \maketitle is output.
982                 intitle_context_ = it.paragraph().layout().intitle;
983                 // Also check embedding layouts
984                 size_t const n = it.depth();
985                 for (size_t i = 0; i < n; ++i) {
986                         if (it[i].paragraph().layout().intitle) {
987                                 intitle_context_ = true;
988                                 break;
989                         }
990                 }
991         } else {
992                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
993                 // Note that we do not need to call:
994                 //      tclass.counters().clearLastLayout()
995                 // since we are saving and restoring the existing counters, etc.
996                 Counters savecnt = tclass.counters();
997                 tclass.counters().reset();
998                 // we need float information even in note insets (#9760)
999                 tclass.counters().current_float(savecnt.current_float());
1000                 tclass.counters().isSubfloat(savecnt.isSubfloat());
1001                 buffer().updateBuffer(it2, utype, deleted);
1002                 tclass.counters() = move(savecnt);
1003         }
1004 }
1005
1006
1007 void InsetText::toString(odocstream & os) const
1008 {
1009         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1010 }
1011
1012
1013 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1014                                                         bool const shorten) const
1015 {
1016         if (!getLayout().isInToc())
1017                 return;
1018         text().forOutliner(os, maxlen, shorten);
1019 }
1020
1021
1022 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1023                                                  UpdateType utype, TocBackend & backend) const
1024 {
1025         DocIterator dit = cdit;
1026         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1027         iterateForToc(dit, output_active, utype, backend);
1028 }
1029
1030
1031 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1032                                                           UpdateType utype, TocBackend & backend) const
1033 {
1034         DocIterator dit = cdit;
1035         // This also ensures that any document has a table of contents
1036         shared_ptr<Toc> toc = backend.toc("tableofcontents");
1037
1038         BufferParams const & bufparams = buffer_->params();
1039         int const min_toclevel = bufparams.documentClass().min_toclevel();
1040         // we really should have done this before we got here, but it
1041         // can't hurt too much to do it again
1042         bool const doing_output = output_active && producesOutput();
1043
1044         // For each paragraph,
1045         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1046         //   paragraphs as needed.
1047         // * Traverse its insets and let them add their toc items
1048         // * Compute the main table of contents (this is hardcoded)
1049         // * Add the list of changes
1050         ParagraphList const & pars = paragraphs();
1051         pit_type pend = paragraphs().size();
1052         // Record pairs {start,end} of where a toc item was opened for a paragraph
1053         // and where it must be closed
1054         stack<pair<pit_type, pit_type>> addtotoc_stack;
1055
1056         for (pit_type pit = 0; pit != pend; ++pit) {
1057                 Paragraph const & par = pars[pit];
1058                 dit.pit() = pit;
1059                 dit.pos() = 0;
1060
1061                 // Custom AddToToc in paragraph layouts (i.e. theorems)
1062                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1063                         pit_type end =
1064                                 openAddToTocForParagraph(pit, dit, output_active, backend);
1065                         addtotoc_stack.push({pit, end});
1066                 }
1067
1068                 // If we find an InsetArgument that is supposed to provide the TOC caption,
1069                 // we'll save it for use later.
1070                 InsetArgument const * arginset = nullptr;
1071                 for (auto const & table : par.insetList()) {
1072                         dit.pos() = table.pos;
1073                         table.inset->addToToc(dit, doing_output, utype, backend);
1074                         if (InsetArgument const * x = table.inset->asInsetArgument())
1075                                 if (x->isTocCaption())
1076                                         arginset = x;
1077                 }
1078
1079                 // End custom AddToToc in paragraph layouts
1080                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1081                         // execute the closing function
1082                         closeAddToTocForParagraph(addtotoc_stack.top().first,
1083                                                   addtotoc_stack.top().second, backend);
1084                         addtotoc_stack.pop();
1085                 }
1086
1087                 // now the toc entry for the paragraph in the main table of contents
1088                 int const toclevel = text().getTocLevel(pit);
1089                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1090                         // insert this into the table of contents
1091                         docstring tocstring;
1092                         int const length = (doing_output && utype == OutputUpdate) ?
1093                                 INT_MAX : TOC_ENTRY_LENGTH;
1094                         if (arginset) {
1095                                 tocstring = par.labelString();
1096                                 if (!tocstring.empty())
1097                                         tocstring += ' ';
1098                                 arginset->text().forOutliner(tocstring, length);
1099                         } else
1100                                 par.forOutliner(tocstring, length);
1101                         dit.pos() = 0;
1102                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1103                                                tocstring, doing_output));
1104                 }
1105
1106                 // And now the list of changes.
1107                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1108         }
1109 }
1110
1111
1112 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1113                                              DocIterator const & dit,
1114                                              bool output_active,
1115                                              TocBackend & backend) const
1116 {
1117         Paragraph const & par = paragraphs()[pit];
1118         TocBuilder & b = backend.builder(par.layout().tocType());
1119         docstring const & label = par.labelString();
1120         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1121         return text().lastInSequence(pit);
1122 }
1123
1124
1125 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1126                                           TocBackend & backend) const
1127 {
1128         Paragraph const & par = paragraphs()[start];
1129         TocBuilder & b = backend.builder(par.layout().tocType());
1130         if (par.layout().isTocCaption()) {
1131                 docstring str;
1132                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1133                 b.argumentItem(str);
1134         }
1135         b.pop();
1136 }
1137
1138
1139 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1140 {
1141         if (buffer().isClean())
1142                 return Inset::notifyCursorLeaves(old, cur);
1143
1144         // find text inset in old cursor
1145         Cursor insetCur = old;
1146         int scriptSlice = insetCur.find(this);
1147         // we can try to continue here. returning true means
1148         // the cursor is "now" invalid. which it was.
1149         LASSERT(scriptSlice != -1, return true);
1150         insetCur.cutOff(scriptSlice);
1151         LASSERT(&insetCur.inset() == this, return true);
1152
1153         // update the old paragraph's words
1154         insetCur.paragraph().updateWords();
1155
1156         return Inset::notifyCursorLeaves(old, cur);
1157 }
1158
1159
1160 bool InsetText::completionSupported(Cursor const & cur) const
1161 {
1162         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1163         return text_.completionSupported(cur);
1164 }
1165
1166
1167 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1168 {
1169         return completionSupported(cur);
1170 }
1171
1172
1173 bool InsetText::automaticInlineCompletion() const
1174 {
1175         return lyxrc.completion_inline_text;
1176 }
1177
1178
1179 bool InsetText::automaticPopupCompletion() const
1180 {
1181         return lyxrc.completion_popup_text;
1182 }
1183
1184
1185 bool InsetText::showCompletionCursor() const
1186 {
1187         return lyxrc.completion_cursor_text;
1188 }
1189
1190
1191 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1192 {
1193         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1194 }
1195
1196
1197 docstring InsetText::completionPrefix(Cursor const & cur) const
1198 {
1199         if (!completionSupported(cur))
1200                 return docstring();
1201         return text_.completionPrefix(cur);
1202 }
1203
1204
1205 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1206         bool finished)
1207 {
1208         if (!completionSupported(cur))
1209                 return false;
1210
1211         return text_.insertCompletion(cur, s, finished);
1212 }
1213
1214
1215 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1216         Dimension & dim) const
1217 {
1218         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1219         tm.completionPosAndDim(cur, x, y, dim);
1220 }
1221
1222
1223 string InsetText::contextMenu(BufferView const &, int, int) const
1224 {
1225         string context_menu = contextMenuName();
1226         if (context_menu != InsetText::contextMenuName())
1227                 context_menu += ";" + InsetText::contextMenuName();
1228         return context_menu;
1229 }
1230
1231
1232 string InsetText::contextMenuName() const
1233 {
1234         return "context-edit";
1235 }
1236
1237
1238 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1239 {
1240         OutputParams rp(&buffer().params().encoding());
1241         rp.for_tooltip = true;
1242         odocstringstream oss;
1243         oss << prefix;
1244
1245         ParagraphList::const_iterator beg = paragraphs().begin();
1246         ParagraphList::const_iterator end = paragraphs().end();
1247         ParagraphList::const_iterator it = beg;
1248         bool ref_printed = false;
1249
1250         for (; it != end; ++it) {
1251                 if (it != beg)
1252                         oss << '\n';
1253                 if ((*it).isRTL(buffer().params()))
1254                         oss << "<div dir=\"rtl\">";
1255                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1256                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1257                         break;
1258         }
1259         docstring str = oss.str();
1260         if (isChanged())
1261                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1262         support::truncateWithEllipsis(str, len);
1263         return str;
1264 }
1265
1266
1267 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1268 {
1269         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1270 }
1271
1272
1273 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1274 {
1275         // Nested cprotect content needs \cprotect
1276         // on each level
1277         if (producesOutput() && hasCProtectContent(fragile))
1278                 return true;
1279
1280         // Environments generally need cprotection in fragile context
1281         if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1282                 return true;
1283
1284         if (!getLayout().needsCProtect())
1285                 return false;
1286
1287         // Environments and "no latex" types (e.g., knitr chunks)
1288         // need cprotection regardless the content
1289         if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1290                 return true;
1291
1292         // If the inset does not produce output (e.g. Note or Branch),
1293         // we can ignore the contained paragraphs
1294         if (!producesOutput())
1295                 return false;
1296
1297         // Commands need cprotection if they contain specific chars
1298         int const nchars_escape = 9;
1299         static char_type const chars_escape[nchars_escape] = {
1300                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1301
1302         ParagraphList const & pars = paragraphs();
1303         pit_type pend = pit_type(paragraphs().size());
1304
1305         for (pit_type pit = 0; pit != pend; ++pit) {
1306                 Paragraph const & par = pars[size_type(pit)];
1307                 if (par.needsCProtection(fragile))
1308                         return true;
1309                 docstring const par_str = par.asString();
1310                 for (int k = 0; k < nchars_escape; k++) {
1311                         if (contains(par_str, chars_escape[k]))
1312                                 return true;
1313                 }
1314         }
1315         return false;
1316 }
1317
1318 } // namespace lyx