]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Whitespace
[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_DISSOLVE: {
324                 bool const main_inset = text_.isMainText();
325                 bool const target_inset = cmd.argument().empty()
326                         || cmd.getArg(0) == insetName(lyxCode());
327
328                 if (!main_inset && target_inset) {
329                         // Text::dissolveInset assumes that the cursor
330                         // is inside the Inset.
331                         if (&cur.inset() != this)
332                                 cur.pushBackward(*this);
333                         cur.beginUndoGroup();
334                         text_.dispatch(cur, cmd);
335                         cur.endUndoGroup();
336                 } else
337                         cur.undispatched();
338                 break;
339         }
340
341         default:
342                 text_.dispatch(cur, cmd);
343         }
344
345         if (!cur.result().dispatched())
346                 Inset::doDispatch(cur, cmd);
347 }
348
349
350 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
351         FuncStatus & status) const
352 {
353         switch (cmd.action()) {
354         case LFUN_INSET_DISSOLVE: {
355                 bool const main_inset = text_.isMainText();
356                 bool const target_inset = cmd.argument().empty()
357                         || cmd.getArg(0) == insetName(lyxCode());
358
359                 if (target_inset)
360                         status.setEnabled(!main_inset);
361                 return target_inset;
362         }
363
364         case LFUN_ARGUMENT_INSERT: {
365                 string const arg = cmd.getArg(0);
366                 if (arg.empty()) {
367                         status.setEnabled(false);
368                         return true;
369                 }
370                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
371                         return text_.getStatus(cur, cmd, status);
372
373                 Layout::LaTeXArgMap args = getLayout().args();
374                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
375                 if (lait != args.end()) {
376                         status.setEnabled(true);
377                         for (Paragraph const & par : paragraphs())
378                                 for (auto const & table : par.insetList())
379                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
380                                                 if (ins->name() == arg) {
381                                                         // we have this already
382                                                         status.setEnabled(false);
383                                                         return true;
384                                                 }
385                 } else
386                         status.setEnabled(false);
387                 return true;
388         }
389
390         default:
391                 // Dispatch only to text_ if the cursor is inside
392                 // the text_. It is not for context menus (bug 5797).
393                 bool ret = false;
394                 if (cur.text() == &text_)
395                         ret = text_.getStatus(cur, cmd, status);
396
397                 if (!ret)
398                         ret = Inset::getStatus(cur, cmd, status);
399                 return ret;
400         }
401 }
402
403
404 void InsetText::fixParagraphsFont()
405 {
406         Font font(inherit_font, buffer().params().language);
407         font.setLanguage(latex_language);
408         ParagraphList::iterator par = paragraphs().begin();
409         ParagraphList::iterator const end = paragraphs().end();
410         while (par != end) {
411                 if (par->isPassThru())
412                         par->resetFonts(font);
413                 if (!par->allowParagraphCustomization())
414                         par->params().clear();
415                 ++par;
416         }
417 }
418
419
420 // bool InsetText::isChanged() const
421 // {
422 //      ParagraphList::const_iterator pit = paragraphs().begin();
423 //      ParagraphList::const_iterator end = paragraphs().end();
424 //      for (; pit != end; ++pit) {
425 //              if (pit->isChanged())
426 //                      return true;
427 //      }
428 //      return false;
429 // }
430
431
432 void InsetText::setChange(Change const & change)
433 {
434         ParagraphList::iterator pit = paragraphs().begin();
435         ParagraphList::iterator end = paragraphs().end();
436         for (; pit != end; ++pit) {
437                 pit->setChange(change);
438         }
439 }
440
441
442 void InsetText::acceptChanges()
443 {
444         text_.acceptChanges();
445 }
446
447
448 void InsetText::rejectChanges()
449 {
450         text_.rejectChanges();
451 }
452
453
454 void InsetText::validate(LaTeXFeatures & features) const
455 {
456         features.useInsetLayout(getLayout());
457         for (Paragraph const & p : paragraphs())
458                 p.validate(features);
459 }
460
461
462 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
463 {
464         // This implements the standard way of handling the LaTeX
465         // output of a text inset, either a command or an
466         // environment. Standard collapsible insets should not
467         // redefine this, non-standard ones may call this.
468         InsetLayout const & il = getLayout();
469         if (il.forceOwnlines())
470                 os << breakln;
471         bool needendgroup = false;
472         if (!il.latexname().empty()) {
473                 if (il.latextype() == InsetLaTeXType::COMMAND) {
474                         // FIXME UNICODE
475                         // FIXME \protect should only be used for fragile
476                         //    commands, but we do not provide this information yet.
477                         if (hasCProtectContent(runparams.moving_arg)) {
478                                 if (contains(runparams.active_chars, '^')) {
479                                         // cprotect relies on ^ being on catcode 7
480                                         os << "\\begingroup\\catcode`\\^=7";
481                                         needendgroup = true;
482                                 }
483                                 os << "\\cprotect";
484                         } else if (runparams.moving_arg)
485                                 os << "\\protect";
486                         os << '\\' << from_utf8(il.latexname());
487                         if (!il.latexargs().empty())
488                                 getArgs(os, runparams);
489                         if (!il.latexparam().empty())
490                                 os << from_utf8(il.latexparam());
491                         os << '{';
492                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
493                         if (il.isDisplay())
494                                 os << breakln;
495                         else
496                                 os << safebreakln;
497                         if (runparams.lastid != -1)
498                                 os.texrow().start(runparams.lastid,
499                                                   runparams.lastpos);
500                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
501                         if (!il.latexargs().empty())
502                                 getArgs(os, runparams);
503                         if (!il.latexparam().empty())
504                                 os << from_utf8(il.latexparam());
505                         os << '\n';
506                 }
507         } else {
508                 if (!il.latexargs().empty())
509                         getArgs(os, runparams);
510                 if (!il.latexparam().empty())
511                         os << from_utf8(il.latexparam());
512         }
513
514         if (!il.leftdelim().empty())
515                 os << il.leftdelim();
516
517         OutputParams rp = runparams;
518         if (isPassThru())
519                 rp.pass_thru = true;
520         if (il.isNeedProtect())
521                 rp.moving_arg = true;
522         if (il.isNeedMBoxProtect())
523                 ++rp.inulemcmd;
524         if (!il.passThruChars().empty())
525                 rp.pass_thru_chars += il.passThruChars();
526         if (!il.newlineCmd().empty())
527                 rp.newlinecmd = il.newlineCmd();
528         rp.par_begin = 0;
529         rp.par_end = paragraphs().size();
530
531         // Output the contents of the inset
532         latexParagraphs(buffer(), text_, os, rp);
533         runparams.encoding = rp.encoding;
534         // Pass the post_macros upstream
535         runparams.post_macro = rp.post_macro;
536         // These need to be passed upstream as well
537         runparams.need_maketitle = rp.need_maketitle;
538         runparams.have_maketitle = rp.have_maketitle;
539
540         if (!il.rightdelim().empty())
541                 os << il.rightdelim();
542
543         if (!il.latexname().empty()) {
544                 if (il.latextype() == InsetLaTeXType::COMMAND) {
545                         os << "}";
546                         if (!il.postcommandargs().empty())
547                                 getArgs(os, runparams, true);
548                         if (needendgroup)
549                                 os << "\\endgroup";
550                 } else if (il.latextype() == InsetLaTeXType::ENVIRONMENT) {
551                         // A comment environment doesn't need a % before \n\end
552                         if (il.isDisplay() || runparams.inComment)
553                                 os << breakln;
554                         else
555                                 os << safebreakln;
556                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
557                         if (!il.isDisplay())
558                                 os.protectSpace(true);
559                 }
560         }
561         if (il.forceOwnlines())
562                 os << breakln;
563 }
564
565
566 int InsetText::plaintext(odocstringstream & os,
567         OutputParams const & runparams, size_t max_length) const
568 {
569         ParagraphList::const_iterator beg = paragraphs().begin();
570         ParagraphList::const_iterator end = paragraphs().end();
571         ParagraphList::const_iterator it = beg;
572         bool ref_printed = false;
573         int len = 0;
574         for (; it != end; ++it) {
575                 if (it != beg) {
576                         os << '\n';
577                         if (runparams.linelen > 0 && !getLayout().parbreakIsNewline())
578                                 os << '\n';
579                 }
580                 odocstringstream oss;
581                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
582                 docstring const str = oss.str();
583                 os << str;
584                 // FIXME: len is not computed fully correctly; in principle,
585                 // we have to count the characters after the last '\n'
586                 len = str.size();
587                 if (os.str().size() >= max_length)
588                         break;
589         }
590
591         return len;
592 }
593
594
595
596 void InsetText::docbook(XMLStream & xs, OutputParams const & rp) const
597 {
598         docbook(xs, rp, WriteEverything);
599 }
600
601
602 void InsetText::docbook(XMLStream & xs, OutputParams const & rp, XHTMLOptions opts) const
603 {
604         // we will always want to output all our paragraphs when we are
605         // called this way.
606         OutputParams runparams = rp;
607         runparams.par_begin = 0;
608         runparams.par_end = text().paragraphs().size();
609
610         if (undefined()) {
611                 xs.startDivision(false);
612                 docbookParagraphs(text_, buffer(), xs, runparams);
613                 xs.endDivision();
614                 return;
615         }
616
617         InsetLayout const & il = getLayout();
618
619         // Maybe this is an <info> paragraph that should not be generated at all (i.e. right now, its place is somewhere
620         // else, typically outside the current paragraph).
621         if (!rp.docbook_generate_info && il.docbookininfo() != "never")
622                 return;
623
624         // In some cases, the input parameters must be overridden for outer tags.
625         bool writeOuterTag = opts & WriteOuterTag;
626         if (writeOuterTag) {
627                 // For each paragraph, if there are only Bibitems and the corresponding text, don't write the outer tags.
628                 bool allBibitems = std::all_of(text().paragraphs().begin(), text().paragraphs().end(), [](Paragraph const & par) {
629                         auto nInsets = std::distance(par.insetList().begin(), par.insetList().end());
630                         auto parSize = (size_t) par.size();
631                         return nInsets == 1 && parSize > 1 && par.insetList().begin()->inset->lyxCode() == BIBITEM_CODE;
632                 });
633                 writeOuterTag = !allBibitems;
634         }
635
636         // Detect arguments that should be output before the paragraph.
637         // Don't reuse runparams.docbook_prepended_arguments, as the same object is used in InsetArgument to determine
638         // whether the inset should be output or not, whatever the context (i.e. position with respect to the wrapper).
639         std::set<InsetArgument const *> prependedArguments;
640         for (auto const & par : paragraphs()) {
641                 for (pos_type i = 0; i < par.size(); ++i) {
642                         if (par.getInset(i) && par.getInset(i)->lyxCode() == ARG_CODE) {
643                                 InsetArgument const *arg = par.getInset(i)->asInsetArgument();
644                                 if (arg->docbookargumentbeforemaintag())
645                                         prependedArguments.insert(par.getInset(i)->asInsetArgument());
646                         }
647                 }
648         }
649
650         // Start outputting this inset.
651         // - First, wrapper around the inset and its main tag.
652         if (writeOuterTag) {
653                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
654                         xml::openTag(xs, il.docbookwrappertag(), il.docbookwrapperattr(), il.docbookwrappertagtype());
655
656                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE") {
657                         docstring attrs = docstring();
658                         if (!il.docbookattr().empty())
659                                 attrs += from_ascii(il.docbookattr());
660                         if (il.docbooktag() == "link")
661                                 attrs += from_ascii(" xlink:href=\"") + text_.asString() + from_ascii("\"");
662                         xml::openTag(xs, il.docbooktag(), attrs, il.docbooktagtype());
663                 }
664         }
665
666         // - Think about the arguments.
667         OutputParams np = runparams;
668         np.docbook_in_par = true;
669         for (auto const & arg : prependedArguments)
670                 arg->docbook(xs, np);
671
672         // - Mark the newly generated arguments are not-to-be-generated-again.
673         runparams.docbook_prepended_arguments = std::move(prependedArguments);
674
675         // - Deal with the first item.
676         // TODO: in things like SciPoster, this should also check if the item tag is allowed. Hard to formalise for now...
677         if (writeOuterTag) {
678                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
679                         xml::openTag(xs, il.docbookitemwrappertag(), il.docbookitemwrapperattr(), il.docbookitemwrappertagtype());
680
681                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
682                         xml::openTag(xs, il.docbookitemtag(), il.docbookitemattr(), il.docbookitemtagtype());
683         }
684
685         // No need for labels that are generated from counters. They should be handled by the external DocBook processor.
686
687         // With respect to XHTML, paragraphs are still allowed here.
688         if (!allowMultiPar())
689                 runparams.docbook_make_pars = false;
690         if (il.isPassThru())
691                 runparams.pass_thru = true;
692
693         // - Write the main content of the inset.
694         xs.startDivision(false);
695         docbookParagraphs(text_, buffer(), xs, runparams);
696         xs.endDivision();
697
698         // - Close the required tags.
699         if (writeOuterTag) {
700                 if (!il.docbookitemtag().empty() && il.docbookitemtag() != "NONE" && il.docbookitemtag() != "IGNORE")
701                         xml::closeTag(xs, il.docbookitemtag(), il.docbookitemtagtype());
702
703                 if (!il.docbookitemwrappertag().empty() && il.docbookitemwrappertag() != "NONE" && il.docbookitemwrappertag() != "IGNORE")
704                         xml::closeTag(xs, il.docbookitemwrappertag(), il.docbookitemwrappertagtype());
705
706                 if (!il.docbooktag().empty() && il.docbooktag() != "NONE" && il.docbooktag() != "IGNORE")
707                         xml::closeTag(xs, il.docbooktag(), il.docbooktagtype());
708
709                 if (!il.docbookwrappertag().empty() && il.docbookwrappertag() != "NONE" && il.docbookwrappertag() != "IGNORE")
710                         xml::closeTag(xs, il.docbookwrappertag(), il.docbookwrappertagtype());
711         }
712 }
713
714
715 docstring InsetText::xhtml(XMLStream & xs, OutputParams const & runparams) const
716 {
717         return insetAsXHTML(xs, runparams, WriteEverything);
718 }
719
720
721 // FIXME XHTML
722 // There are cases where we may need to close open fonts and such
723 // and then re-open them when we are done. This would be the case, e.g.,
724 // if we were otherwise about to write:
725 //              <em>word <div class='foot'>footnote text.</div> emph</em>
726 // The problem isn't so much that the footnote text will get emphasized:
727 // we can handle that with CSS. The problem is that this is invalid XHTML.
728 // One solution would be to make the footnote <span>, but the problem is
729 // completely general, and so we'd have to make absolutely everything into
730 // span. What I think will work is to check if we're about to write "div" and,
731 // if so, try to close fonts, etc.
732 // There are probably limits to how well we can do here, though, and we will
733 // have to rely upon users not putting footnotes inside noun-type insets.
734 docstring InsetText::insetAsXHTML(XMLStream & xs, OutputParams const & rp,
735                                   XHTMLOptions opts) const
736 {
737         // we will always want to output all our paragraphs when we are
738         // called this way.
739         OutputParams runparams = rp;
740         runparams.par_begin = 0;
741         runparams.par_end = text().paragraphs().size();
742
743         if (undefined()) {
744                 xs.startDivision(false);
745                 xhtmlParagraphs(text_, buffer(), xs, runparams);
746                 xs.endDivision();
747                 return docstring();
748         }
749
750         InsetLayout const & il = getLayout();
751         if (opts & WriteOuterTag)
752                 xs << xml::StartTag(il.htmltag(), il.htmlattr());
753
754         if ((opts & WriteLabel) && !il.counter().empty()) {
755                 BufferParams const & bp = buffer().masterBuffer()->params();
756                 Counters & cntrs = bp.documentClass().counters();
757                 cntrs.step(il.counter(), OutputUpdate);
758                 // FIXME: translate to paragraph language
759                 if (!il.htmllabel().empty()) {
760                         docstring const lbl =
761                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
762                         // FIXME is this check necessary?
763                         if (!lbl.empty()) {
764                                 xs << xml::StartTag(il.htmllabeltag(), il.htmllabelattr());
765                                 xs << lbl;
766                                 xs << xml::EndTag(il.htmllabeltag());
767                         }
768                 }
769         }
770
771         if (opts & WriteInnerTag)
772                 xs << xml::StartTag(il.htmlinnertag(), il.htmlinnerattr());
773
774         // we will eventually lose information about the containing inset
775         if (!allowMultiPar() || opts == JustText)
776                 runparams.html_make_pars = false;
777         if (il.isPassThru())
778                 runparams.pass_thru = true;
779
780         xs.startDivision(false);
781         xhtmlParagraphs(text_, buffer(), xs, runparams);
782         xs.endDivision();
783
784         if (opts & WriteInnerTag)
785                 xs << xml::EndTag(il.htmlinnertag());
786
787         if (opts & WriteOuterTag)
788                 xs << xml::EndTag(il.htmltag());
789
790         return docstring();
791 }
792
793
794 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
795                         bool const post) const
796 {
797         OutputParams runparams = runparams_in;
798         runparams.local_font =
799                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
800         if (isPassThru())
801                 runparams.pass_thru = true;
802         if (post)
803                 latexArgInsetsForParent(paragraphs(), os, runparams,
804                                         getLayout().postcommandargs(), "post:");
805         else
806                 latexArgInsetsForParent(paragraphs(), os, runparams,
807                                         getLayout().latexargs());
808 }
809
810
811 void InsetText::cursorPos(BufferView const & bv,
812                 CursorSlice const & sl, bool boundary, int & x, int & y) const
813 {
814         x = bv.textMetrics(&text_).cursorX(sl, boundary) + leftOffset(&bv);
815         y = bv.textMetrics(&text_).cursorY(sl, boundary);
816 }
817
818
819 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
820 {
821         clear();
822         Paragraph & first = paragraphs().front();
823         for (unsigned int i = 0; i < data.length(); ++i)
824                 first.insertChar(i, data[i], font, trackChanges);
825 }
826
827
828 void InsetText::setDrawFrame(bool flag)
829 {
830         drawFrame_ = flag;
831 }
832
833
834 ColorCode InsetText::frameColor() const
835 {
836         return frame_color_;
837 }
838
839
840 void InsetText::setFrameColor(ColorCode col)
841 {
842         frame_color_ = col;
843 }
844
845
846 void InsetText::appendParagraphs(ParagraphList & plist)
847 {
848         // There is little we can do here to keep track of changes.
849         // As of 2006/10/20, appendParagraphs is used exclusively by
850         // LyXTabular::setMultiColumn. In this context, the paragraph break
851         // is lost irreversibly and the appended text doesn't really change
852
853         ParagraphList & pl = paragraphs();
854
855         ParagraphList::iterator pit = plist.begin();
856         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
857         ++pit;
858         mergeParagraph(buffer().params(), pl,
859                        distance(pl.begin(), ins) - 1);
860
861         ParagraphList::iterator const pend = plist.end();
862         for (; pit != pend; ++pit)
863                 pl.push_back(*pit);
864 }
865
866
867 void InsetText::addPreview(DocIterator const & text_inset_pos,
868         PreviewLoader & loader) const
869 {
870         ParagraphList::const_iterator pit = paragraphs().begin();
871         ParagraphList::const_iterator pend = paragraphs().end();
872         int pidx = 0;
873
874         DocIterator inset_pos = text_inset_pos;
875         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
876
877         for (; pit != pend; ++pit, ++pidx) {
878                 InsetList::const_iterator it  = pit->insetList().begin();
879                 InsetList::const_iterator end = pit->insetList().end();
880                 inset_pos.pit() = pidx;
881                 for (; it != end; ++it) {
882                         inset_pos.pos() = it->pos;
883                         it->inset->addPreview(inset_pos, loader);
884                 }
885         }
886 }
887
888
889 ParagraphList const & InsetText::paragraphs() const
890 {
891         return text_.paragraphs();
892 }
893
894
895 ParagraphList & InsetText::paragraphs()
896 {
897         return text_.paragraphs();
898 }
899
900
901 bool InsetText::hasCProtectContent(bool fragile) const
902 {
903         fragile |= getLayout().isNeedProtect();
904         ParagraphList const & pars = paragraphs();
905         pit_type pend = pit_type(paragraphs().size());
906         for (pit_type pit = 0; pit != pend; ++pit) {
907                 Paragraph const & par = pars[size_type(pit)];
908                 if (par.needsCProtection(fragile))
909                         return true;
910         }
911         return false;
912 }
913
914
915 bool InsetText::insetAllowed(InsetCode code) const
916 {
917         switch (code) {
918         // Arguments and (plain) quotes are also allowed in PassThru insets
919         case ARG_CODE:
920         case QUOTE_CODE:
921                 return true;
922         default:
923                 return !isPassThru();
924         }
925 }
926
927
928 bool InsetText::allowSpellCheck() const
929 {
930         return getLayout().spellcheck() && !getLayout().isPassThru();
931 }
932
933
934 bool InsetText::allowMultiPar() const
935 {
936         return getLayout().isMultiPar();
937 }
938
939
940 bool InsetText::forcePlainLayout(idx_type) const
941 {
942         return getLayout().forcePlainLayout();
943 }
944
945
946 bool InsetText::allowParagraphCustomization(idx_type) const
947 {
948         return getLayout().allowParagraphCustomization();
949 }
950
951
952 bool InsetText::forceLocalFontSwitch() const
953 {
954         return getLayout().forceLocalFontSwitch();
955 }
956
957
958 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
959 {
960         ParIterator it2 = it;
961         it2.forwardPos();
962         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
963         if (producesOutput()) {
964                 InsetLayout const & il = getLayout();
965                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
966                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
967                 if (save_layouts) {
968                         // LYXERR0("Entering " << name());
969                         cnt.clearLastLayout();
970                         // FIXME cnt.saveLastCounter()?
971                 }
972                 buffer().updateBuffer(it2, utype, deleted);
973                 if (save_layouts) {
974                         // LYXERR0("Exiting " << name());
975                         cnt.restoreLastLayout();
976                         // FIXME cnt.restoreLastCounter()?
977                 }
978                 // Record in this inset is embedded in a title layout
979                 // This is needed to decide when \maketitle is output.
980                 intitle_context_ = it.paragraph().layout().intitle;
981                 // Also check embedding layouts
982                 size_t const n = it.depth();
983                 for (size_t i = 0; i < n; ++i) {
984                         if (it[i].paragraph().layout().intitle) {
985                                 intitle_context_ = true;
986                                 break;
987                         }
988                 }
989         } else {
990                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
991                 // Note that we do not need to call:
992                 //      tclass.counters().clearLastLayout()
993                 // since we are saving and restoring the existing counters, etc.
994                 Counters savecnt = tclass.counters();
995                 tclass.counters().reset();
996                 // we need float information even in note insets (#9760)
997                 tclass.counters().current_float(savecnt.current_float());
998                 tclass.counters().isSubfloat(savecnt.isSubfloat());
999                 buffer().updateBuffer(it2, utype, deleted);
1000                 tclass.counters() = move(savecnt);
1001         }
1002 }
1003
1004
1005 void InsetText::toString(odocstream & os) const
1006 {
1007         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
1008 }
1009
1010
1011 void InsetText::forOutliner(docstring & os, size_t const maxlen,
1012                                                         bool const shorten) const
1013 {
1014         if (!getLayout().isInToc())
1015                 return;
1016         text().forOutliner(os, maxlen, shorten);
1017 }
1018
1019
1020 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
1021                                                  UpdateType utype, TocBackend & backend) const
1022 {
1023         DocIterator dit = cdit;
1024         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
1025         iterateForToc(dit, output_active, utype, backend);
1026 }
1027
1028
1029 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
1030                                                           UpdateType utype, TocBackend & backend) const
1031 {
1032         DocIterator dit = cdit;
1033         // This also ensures that any document has a table of contents
1034         shared_ptr<Toc> toc = backend.toc("tableofcontents");
1035
1036         BufferParams const & bufparams = buffer_->params();
1037         int const min_toclevel = bufparams.documentClass().min_toclevel();
1038         // we really should have done this before we got here, but it
1039         // can't hurt too much to do it again
1040         bool const doing_output = output_active && producesOutput();
1041
1042         // For each paragraph,
1043         // * Add a toc item for the paragraph if it is AddToToc--merging adjacent
1044         //   paragraphs as needed.
1045         // * Traverse its insets and let them add their toc items
1046         // * Compute the main table of contents (this is hardcoded)
1047         // * Add the list of changes
1048         ParagraphList const & pars = paragraphs();
1049         pit_type pend = paragraphs().size();
1050         // Record pairs {start,end} of where a toc item was opened for a paragraph
1051         // and where it must be closed
1052         stack<pair<pit_type, pit_type>> addtotoc_stack;
1053
1054         for (pit_type pit = 0; pit != pend; ++pit) {
1055                 Paragraph const & par = pars[pit];
1056                 dit.pit() = pit;
1057                 dit.pos() = 0;
1058
1059                 // Custom AddToToc in paragraph layouts (i.e. theorems)
1060                 if (par.layout().addToToc() && text().isFirstInSequence(pit)) {
1061                         pit_type end =
1062                                 openAddToTocForParagraph(pit, dit, output_active, backend);
1063                         addtotoc_stack.push({pit, end});
1064                 }
1065
1066                 // If we find an InsetArgument that is supposed to provide the TOC caption,
1067                 // we'll save it for use later.
1068                 InsetArgument const * arginset = nullptr;
1069                 for (auto const & table : par.insetList()) {
1070                         dit.pos() = table.pos;
1071                         table.inset->addToToc(dit, doing_output, utype, backend);
1072                         if (InsetArgument const * x = table.inset->asInsetArgument())
1073                                 if (x->isTocCaption())
1074                                         arginset = x;
1075                 }
1076
1077                 // End custom AddToToc in paragraph layouts
1078                 while (!addtotoc_stack.empty() && addtotoc_stack.top().second == pit) {
1079                         // execute the closing function
1080                         closeAddToTocForParagraph(addtotoc_stack.top().first,
1081                                                   addtotoc_stack.top().second, backend);
1082                         addtotoc_stack.pop();
1083                 }
1084
1085                 // now the toc entry for the paragraph in the main table of contents
1086                 int const toclevel = text().getTocLevel(pit);
1087                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
1088                         // insert this into the table of contents
1089                         docstring tocstring;
1090                         int const length = (doing_output && utype == OutputUpdate) ?
1091                                 INT_MAX : TOC_ENTRY_LENGTH;
1092                         if (arginset) {
1093                                 tocstring = par.labelString();
1094                                 if (!tocstring.empty())
1095                                         tocstring += ' ';
1096                                 arginset->text().forOutliner(tocstring, length);
1097                         } else
1098                                 par.forOutliner(tocstring, length);
1099                         dit.pos() = 0;
1100                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
1101                                                tocstring, doing_output));
1102                 }
1103
1104                 // And now the list of changes.
1105                 par.addChangesToToc(dit, buffer(), doing_output, backend);
1106         }
1107 }
1108
1109
1110 pit_type InsetText::openAddToTocForParagraph(pit_type pit,
1111                                              DocIterator const & dit,
1112                                              bool output_active,
1113                                              TocBackend & backend) const
1114 {
1115         Paragraph const & par = paragraphs()[pit];
1116         TocBuilder & b = backend.builder(par.layout().tocType());
1117         docstring const & label = par.labelString();
1118         b.pushItem(dit, label + (label.empty() ? "" : " "), output_active);
1119         return text().lastInSequence(pit);
1120 }
1121
1122
1123 void InsetText::closeAddToTocForParagraph(pit_type start, pit_type end,
1124                                           TocBackend & backend) const
1125 {
1126         Paragraph const & par = paragraphs()[start];
1127         TocBuilder & b = backend.builder(par.layout().tocType());
1128         if (par.layout().isTocCaption()) {
1129                 docstring str;
1130                 text().forOutliner(str, TOC_ENTRY_LENGTH, start, end);
1131                 b.argumentItem(str);
1132         }
1133         b.pop();
1134 }
1135
1136
1137 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1138 {
1139         if (buffer().isClean())
1140                 return Inset::notifyCursorLeaves(old, cur);
1141
1142         // find text inset in old cursor
1143         Cursor insetCur = old;
1144         int scriptSlice = insetCur.find(this);
1145         // we can try to continue here. returning true means
1146         // the cursor is "now" invalid. which it was.
1147         LASSERT(scriptSlice != -1, return true);
1148         insetCur.cutOff(scriptSlice);
1149         LASSERT(&insetCur.inset() == this, return true);
1150
1151         // update the old paragraph's words
1152         insetCur.paragraph().updateWords();
1153
1154         return Inset::notifyCursorLeaves(old, cur);
1155 }
1156
1157
1158 bool InsetText::completionSupported(Cursor const & cur) const
1159 {
1160         //LASSERT(&cur.bv().cursor().inset() == this, return false);
1161         return text_.completionSupported(cur);
1162 }
1163
1164
1165 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
1166 {
1167         return completionSupported(cur);
1168 }
1169
1170
1171 bool InsetText::automaticInlineCompletion() const
1172 {
1173         return lyxrc.completion_inline_text;
1174 }
1175
1176
1177 bool InsetText::automaticPopupCompletion() const
1178 {
1179         return lyxrc.completion_popup_text;
1180 }
1181
1182
1183 bool InsetText::showCompletionCursor() const
1184 {
1185         return lyxrc.completion_cursor_text;
1186 }
1187
1188
1189 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
1190 {
1191         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
1192 }
1193
1194
1195 docstring InsetText::completionPrefix(Cursor const & cur) const
1196 {
1197         if (!completionSupported(cur))
1198                 return docstring();
1199         return text_.completionPrefix(cur);
1200 }
1201
1202
1203 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
1204         bool finished)
1205 {
1206         if (!completionSupported(cur))
1207                 return false;
1208
1209         return text_.insertCompletion(cur, s, finished);
1210 }
1211
1212
1213 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
1214         Dimension & dim) const
1215 {
1216         TextMetrics const & tm = cur.bv().textMetrics(&text_);
1217         tm.completionPosAndDim(cur, x, y, dim);
1218 }
1219
1220
1221 string InsetText::contextMenu(BufferView const &, int, int) const
1222 {
1223         string context_menu = contextMenuName();
1224         if (context_menu != InsetText::contextMenuName())
1225                 context_menu += ";" + InsetText::contextMenuName();
1226         return context_menu;
1227 }
1228
1229
1230 string InsetText::contextMenuName() const
1231 {
1232         return "context-edit";
1233 }
1234
1235
1236 docstring InsetText::toolTipText(docstring const & prefix, size_t const len) const
1237 {
1238         OutputParams rp(&buffer().params().encoding());
1239         rp.for_tooltip = true;
1240         odocstringstream oss;
1241         oss << prefix;
1242
1243         ParagraphList::const_iterator beg = paragraphs().begin();
1244         ParagraphList::const_iterator end = paragraphs().end();
1245         ParagraphList::const_iterator it = beg;
1246         bool ref_printed = false;
1247
1248         for (; it != end; ++it) {
1249                 if (it != beg)
1250                         oss << '\n';
1251                 if ((*it).isRTL(buffer().params()))
1252                         oss << "<div dir=\"rtl\">";
1253                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1254                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1255                         break;
1256         }
1257         docstring str = oss.str();
1258         if (isChanged())
1259                 str += from_ascii("\n\n") + _("[contains tracked changes]");
1260         support::truncateWithEllipsis(str, len);
1261         return str;
1262 }
1263
1264
1265 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1266 {
1267         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1268 }
1269
1270
1271 bool InsetText::needsCProtection(bool const maintext, bool const fragile) const
1272 {
1273         // Nested cprotect content needs \cprotect
1274         // on each level
1275         if (producesOutput() && hasCProtectContent(fragile))
1276                 return true;
1277
1278         // Environments generally need cprotection in fragile context
1279         if (fragile && getLayout().latextype() == InsetLaTeXType::ENVIRONMENT)
1280                 return true;
1281
1282         if (!getLayout().needsCProtect())
1283                 return false;
1284
1285         // Environments and "no latex" types (e.g., knitr chunks)
1286         // need cprotection regardless the content
1287         if (!maintext && getLayout().latextype() != InsetLaTeXType::COMMAND)
1288                 return true;
1289
1290         // If the inset does not produce output (e.g. Note or Branch),
1291         // we can ignore the contained paragraphs
1292         if (!producesOutput())
1293                 return false;
1294
1295         // Commands need cprotection if they contain specific chars
1296         int const nchars_escape = 9;
1297         static char_type const chars_escape[nchars_escape] = {
1298                 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
1299
1300         ParagraphList const & pars = paragraphs();
1301         pit_type pend = pit_type(paragraphs().size());
1302
1303         for (pit_type pit = 0; pit != pend; ++pit) {
1304                 Paragraph const & par = pars[size_type(pit)];
1305                 if (par.needsCProtection(fragile))
1306                         return true;
1307                 docstring const par_str = par.asString();
1308                 for (int k = 0; k < nchars_escape; k++) {
1309                         if (contains(par_str, chars_escape[k]))
1310                                 return true;
1311                 }
1312         }
1313         return false;
1314 }
1315
1316 } // namespace lyx