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