]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Rationalise includes
[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 "InsetCaption.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_xhtml.h"
43 #include "OutputParams.h"
44 #include "output_plaintext.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Row.h"
49 #include "sgml.h"
50 #include "TexRow.h"
51 #include "texstream.h"
52 #include "TextClass.h"
53 #include "Text.h"
54 #include "TextMetrics.h"
55 #include "TocBackend.h"
56
57 #include "frontends/alert.h"
58 #include "frontends/Painter.h"
59
60 #include "support/bind.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/RefChanger.h"
67
68 #include <algorithm>
69
70
71 using namespace std;
72 using namespace lyx::support;
73
74
75 namespace lyx {
76
77 using graphics::PreviewLoader;
78
79
80 /////////////////////////////////////////////////////////////////////
81
82 InsetText::InsetText(Buffer * buf, UsePlain type)
83         : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
84         text_(this, type == DefaultLayout)
85 {
86 }
87
88
89 InsetText::InsetText(InsetText const & in)
90         : Inset(in), text_(this, in.text_)
91 {
92         drawFrame_ = in.drawFrame_;
93         frame_color_ = in.frame_color_;
94 }
95
96
97 void InsetText::setBuffer(Buffer & buf)
98 {
99         ParagraphList::iterator end = paragraphs().end();
100         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
101                 it->setBuffer(buf);
102         Inset::setBuffer(buf);
103 }
104
105
106 void InsetText::setMacrocontextPositionRecursive(DocIterator const & pos)
107 {
108         text_.setMacrocontextPosition(pos);
109
110         ParagraphList::const_iterator pit = paragraphs().begin();
111         ParagraphList::const_iterator pend = paragraphs().end();
112         for (; pit != pend; ++pit) {
113                 InsetList::const_iterator iit = pit->insetList().begin();
114                 InsetList::const_iterator end = pit->insetList().end();
115                 for (; iit != end; ++iit) {
116                         if (InsetText * txt = iit->inset->asInsetText()) {
117                                 DocIterator ppos(pos);
118                                 ppos.push_back(CursorSlice(*txt));
119                                 iit->inset->asInsetText()->setMacrocontextPositionRecursive(ppos);
120                         }
121                 }
122         }
123 }
124
125
126 void InsetText::clear()
127 {
128         ParagraphList & pars = paragraphs();
129         LBUFERR(!pars.empty());
130
131         // This is a gross hack...
132         Layout const & old_layout = pars.begin()->layout();
133
134         pars.clear();
135         pars.push_back(Paragraph());
136         pars.begin()->setInsetOwner(this);
137         pars.begin()->setLayout(old_layout);
138 }
139
140
141 Dimension const InsetText::dimension(BufferView const & bv) const
142 {
143         TextMetrics const & tm = bv.textMetrics(&text_);
144         Dimension dim = tm.dimension();
145         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
146         dim.des += TEXT_TO_INSET_OFFSET;
147         dim.asc += TEXT_TO_INSET_OFFSET;
148         return dim;
149 }
150
151
152 void InsetText::write(ostream & os) const
153 {
154         os << "Text\n";
155         text_.write(os);
156 }
157
158
159 void InsetText::read(Lexer & lex)
160 {
161         clear();
162
163         // delete the initial paragraph
164         Paragraph oldpar = *paragraphs().begin();
165         paragraphs().clear();
166         ErrorList errorList;
167         lex.setContext("InsetText::read");
168         bool res = text_.read(lex, errorList, this);
169
170         if (!res)
171                 lex.printError("Missing \\end_inset at this point. ");
172
173         // sanity check
174         // ensure we have at least one paragraph.
175         if (paragraphs().empty())
176                 paragraphs().push_back(oldpar);
177         // Force default font, if so requested
178         // This avoids paragraphs in buffer language that would have a
179         // foreign language after a document language change, and it ensures
180         // that all new text in ERT and similar gets the "latex" language,
181         // since new text inherits the language from the last position of the
182         // existing text.  As a side effect this makes us also robust against
183         // bugs in LyX that might lead to font changes in ERT in .lyx files.
184         fixParagraphsFont();
185 }
186
187
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 {
190         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191
192         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193
194         // Hand font through to contained lyxtext:
195         tm.font_.fontInfo() = mi.base.font;
196         mi.base.textwidth -= 2 * TEXT_TO_INSET_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 += 2 * TEXT_TO_INSET_OFFSET;
209         dim.asc += TEXT_TO_INSET_OFFSET;
210         dim.des += TEXT_TO_INSET_OFFSET;
211         dim.wid += 2 * TEXT_TO_INSET_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 w = tm.width() + TEXT_TO_INSET_OFFSET;
220         int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
221         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
222         int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
223         bool change_drawn = false;
224         if (drawFrame_ || pi.full_repaint) {
225                 if (pi.full_repaint)
226                         pi.pain.fillRectangle(xframe, yframe, w, h,
227                                 pi.backgroundColor(this));
228
229                 // Change color of the frame in tracked changes, like for tabulars.
230         // Only do so if the color is not custom. But do so even if RowPainter
231         // handles the strike-through already.
232                 Color c;
233                 if (pi.change_.changed()
234                     // Originally, these are the colors with role Text, from role() in
235                     // ColorCache.cpp.  The code is duplicated to avoid depending on Qt
236                     // types, and also maybe it need not match in the future.
237                     && (frameColor() == Color_foreground
238                         || frameColor() == Color_cursor
239                         || frameColor() == Color_preview
240                         || frameColor() == Color_tabularline
241                         || frameColor() == Color_previewframe)) {
242                         c = pi.change_.color();
243                         change_drawn = true;
244                 } else
245                         c = frameColor();
246                 if (drawFrame_)
247                         pi.pain.rectangle(xframe, yframe, w, h, c);
248         }
249         {
250                 Changer dummy = make_change(pi.background_color,
251                                             pi.backgroundColor(this, false));
252                 // The change tracking cue must not be inherited
253                 Changer dummy2 = make_change(pi.change_, Change());
254                 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
255         }
256         if (canPaintChange(*pi.base.bv) && (!change_drawn || pi.change_.deleted()))
257                 // Do not draw the change tracking cue if already done by RowPainter and
258                 // do not draw the cue for INSERTED if the information is already in the
259                 // color of the frame
260                 pi.change_.paintCue(pi, xframe, yframe, xframe + w, yframe + h);
261 }
262
263
264 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
265 {
266         pit_type const pit = front ? 0 : paragraphs().size() - 1;
267         pos_type pos = front ? 0 : paragraphs().back().size();
268
269         // if visual information is not to be ignored, move to extreme right/left
270         if (entry_from != ENTRY_DIRECTION_IGNORE) {
271                 Cursor temp_cur = cur;
272                 temp_cur.pit() = pit;
273                 temp_cur.pos() = pos;
274                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
275                 pos = temp_cur.pos();
276         }
277
278         cur.top().setPitPos(pit, pos);
279         cur.finishUndo();
280 }
281
282
283 Inset * InsetText::editXY(Cursor & cur, int x, int y)
284 {
285         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
286 }
287
288
289 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
290 {
291         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
292
293         // See bug #9042, for instance.
294         if (isPassThru() && lyxCode() != ARG_CODE) {
295                 // Force any new text to latex_language FIXME: This
296                 // should only be necessary in constructor, but new
297                 // paragraphs that are created by pressing enter at
298                 // the start of an existing paragraph get the buffer
299                 // language and not latex_language, so we take this
300                 // brute force approach.
301                 cur.current_font.setLanguage(latex_language);
302                 cur.real_current_font.setLanguage(latex_language);
303         }
304
305         switch (cmd.action()) {
306         case LFUN_PASTE:
307         case LFUN_CLIPBOARD_PASTE:
308         case LFUN_SELECTION_PASTE:
309         case LFUN_PRIMARY_SELECTION_PASTE:
310                 text_.dispatch(cur, cmd);
311                 // If we we can only store plain text, we must reset all
312                 // attributes.
313                 // FIXME: Change only the pasted paragraphs
314                 fixParagraphsFont();
315                 break;
316
317         case LFUN_INSET_DISSOLVE: {
318                 bool const main_inset = text_.isMainText();
319                 bool const target_inset = cmd.argument().empty() 
320                         || cmd.getArg(0) == insetName(lyxCode());
321                 // cur.inset() is the tabular when this is a single cell (bug #9954)
322                 bool const one_cell = cur.inset().nargs() == 1;
323
324                 if (!main_inset && target_inset && one_cell) {
325                         // Text::dissolveInset assumes that the cursor
326                         // is inside the Inset.
327                         if (&cur.inset() != this)
328                                 cur.pushBackward(*this);
329                         cur.beginUndoGroup();
330                         text_.dispatch(cur, cmd);
331                         cur.endUndoGroup();
332                 } else
333                         cur.undispatched();
334                 break;
335         }
336
337         default:
338                 text_.dispatch(cur, cmd);
339         }
340         
341         if (!cur.result().dispatched())
342                 Inset::doDispatch(cur, cmd);
343 }
344
345
346 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
347         FuncStatus & status) const
348 {
349         switch (cmd.action()) {
350         case LFUN_INSET_DISSOLVE: {
351                 bool const main_inset = text_.isMainText();
352                 bool const target_inset = cmd.argument().empty() 
353                         || cmd.getArg(0) == insetName(lyxCode());
354                 // cur.inset() is the tabular when this is a single cell (bug #9954)
355                 bool const one_cell = cur.inset().nargs() == 1;
356
357                 if (target_inset)
358                         status.setEnabled(!main_inset && one_cell);
359                 return target_inset;
360         }
361
362         case LFUN_ARGUMENT_INSERT: {
363                 string const arg = cmd.getArg(0);
364                 if (arg.empty()) {
365                         status.setEnabled(false);
366                         return true;
367                 }
368                 if (text_.isMainText() || !cur.paragraph().layout().args().empty())
369                         return text_.getStatus(cur, cmd, status);
370
371                 Layout::LaTeXArgMap args = getLayout().args();
372                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
373                 if (lait != args.end()) {
374                         status.setEnabled(true);
375                         ParagraphList::const_iterator pit = paragraphs().begin();
376                         for (; pit != paragraphs().end(); ++pit) {
377                                 InsetList::const_iterator it = pit->insetList().begin();
378                                 InsetList::const_iterator end = pit->insetList().end();
379                                 for (; it != end; ++it) {
380                                         if (it->inset->lyxCode() == ARG_CODE) {
381                                                 InsetArgument const * ins =
382                                                         static_cast<InsetArgument const *>(it->inset);
383                                                 if (ins->name() == arg) {
384                                                         // we have this already
385                                                         status.setEnabled(false);
386                                                         return true;
387                                                 }
388                                         }
389                                 }
390                         }
391                 } else
392                         status.setEnabled(false);
393                 return true;
394         }
395
396         default:
397                 // Dispatch only to text_ if the cursor is inside
398                 // the text_. It is not for context menus (bug 5797).
399                 bool ret = false;
400                 if (cur.text() == &text_)
401                         ret = text_.getStatus(cur, cmd, status);
402                 
403                 if (!ret)
404                         ret = Inset::getStatus(cur, cmd, status);
405                 return ret;
406         }
407 }
408
409
410 void InsetText::fixParagraphsFont()
411 {
412         Font font(inherit_font, buffer().params().language);
413         font.setLanguage(latex_language);
414         ParagraphList::iterator par = paragraphs().begin();
415         ParagraphList::iterator const end = paragraphs().end();
416         while (par != end) {
417                 if (par->isPassThru())
418                         par->resetFonts(font);
419                 if (!par->allowParagraphCustomization())
420                         par->params().clear();
421                 ++par;
422         }
423 }
424
425
426 void InsetText::setChange(Change const & change)
427 {
428         ParagraphList::iterator pit = paragraphs().begin();
429         ParagraphList::iterator end = paragraphs().end();
430         for (; pit != end; ++pit) {
431                 pit->setChange(change);
432         }
433 }
434
435
436 void InsetText::acceptChanges()
437 {
438         text_.acceptChanges();
439 }
440
441
442 void InsetText::rejectChanges()
443 {
444         text_.rejectChanges();
445 }
446
447
448 void InsetText::validate(LaTeXFeatures & features) const
449 {
450         features.useInsetLayout(getLayout());
451         for (Paragraph const & p : paragraphs())
452                 p.validate(features);
453 }
454
455
456 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
457 {
458         // This implements the standard way of handling the LaTeX
459         // output of a text inset, either a command or an
460         // environment. Standard collapsable insets should not
461         // redefine this, non-standard ones may call this.
462         InsetLayout const & il = getLayout();
463         if (il.forceOwnlines())
464                 os << breakln;
465         if (!il.latexname().empty()) {
466                 if (il.latextype() == InsetLayout::COMMAND) {
467                         // FIXME UNICODE
468                         // FIXME \protect should only be used for fragile
469                         //    commands, but we do not provide this information yet.
470                         if (runparams.moving_arg)
471                                 os << "\\protect";
472                         os << '\\' << from_utf8(il.latexname());
473                         if (!il.latexargs().empty())
474                                 getArgs(os, runparams);
475                         if (!il.latexparam().empty())
476                                 os << from_utf8(il.latexparam());
477                         os << '{';
478                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
479                         if (il.isDisplay())
480                                 os << breakln;
481                         else
482                                 os << safebreakln;
483                         if (runparams.lastid != -1)
484                                 os.texrow().start(runparams.lastid,
485                                                   runparams.lastpos);
486                         os << "\\begin{" << 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 << '\n';
492                 }
493         } else {
494                 if (!il.latexargs().empty())
495                         getArgs(os, runparams);
496                 if (!il.latexparam().empty())
497                         os << from_utf8(il.latexparam());
498         }
499
500         if (!il.leftdelim().empty())
501                 os << il.leftdelim();
502
503         OutputParams rp = runparams;
504         if (isPassThru())
505                 rp.pass_thru = true;
506         if (il.isNeedProtect())
507                 rp.moving_arg = true;
508         if (!il.passThruChars().empty())
509                 rp.pass_thru_chars += il.passThruChars();
510         rp.par_begin = 0;
511         rp.par_end = paragraphs().size();
512
513         // Output the contents of the inset
514         latexParagraphs(buffer(), text_, os, rp);
515         runparams.encoding = rp.encoding;
516
517         if (!il.rightdelim().empty())
518                 os << il.rightdelim();
519
520         if (!il.latexname().empty()) {
521                 if (il.latextype() == InsetLayout::COMMAND) {
522                         os << "}";
523                         if (!il.postcommandargs().empty())
524                                 getArgs(os, runparams, true);
525                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
526                         // A comment environment doesn't need a % before \n\end
527                         if (il.isDisplay() || runparams.inComment)
528                                 os << breakln;
529                         else
530                                 os << safebreakln;
531                         os << "\\end{" << from_utf8(il.latexname()) << "}" << breakln;
532                         if (!il.isDisplay())
533                                 os.protectSpace(true);
534                 }
535         }
536         if (il.forceOwnlines())
537                 os << breakln;
538 }
539
540
541 int InsetText::plaintext(odocstringstream & os,
542         OutputParams const & runparams, size_t max_length) const
543 {
544         ParagraphList::const_iterator beg = paragraphs().begin();
545         ParagraphList::const_iterator end = paragraphs().end();
546         ParagraphList::const_iterator it = beg;
547         bool ref_printed = false;
548         int len = 0;
549         for (; it != end; ++it) {
550                 if (it != beg) {
551                         os << '\n';
552                         if (runparams.linelen > 0)
553                                 os << '\n';
554                 }
555                 odocstringstream oss;
556                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
557                 docstring const str = oss.str();
558                 os << str;
559                 // FIXME: len is not computed fully correctly; in principle,
560                 // we have to count the characters after the last '\n'
561                 len = str.size();
562                 if (os.str().size() >= max_length)
563                         break;
564         }
565
566         return len;
567 }
568
569
570 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
571 {
572         ParagraphList::const_iterator const beg = paragraphs().begin();
573
574         if (!undefined())
575                 sgml::openTag(os, getLayout().latexname(),
576                               beg->getID(buffer(), runparams) + getLayout().latexparam());
577
578         docbookParagraphs(text_, buffer(), os, runparams);
579
580         if (!undefined())
581                 sgml::closeTag(os, getLayout().latexname());
582
583         return 0;
584 }
585
586
587 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
588 {
589         return insetAsXHTML(xs, runparams, WriteEverything);
590 }
591
592
593 // FIXME XHTML
594 // There are cases where we may need to close open fonts and such
595 // and then re-open them when we are done. This would be the case, e.g.,
596 // if we were otherwise about to write:
597 //              <em>word <div class='foot'>footnote text.</div> emph</em>
598 // The problem isn't so much that the footnote text will get emphasized:
599 // we can handle that with CSS. The problem is that this is invalid XHTML.
600 // One solution would be to make the footnote <span>, but the problem is
601 // completely general, and so we'd have to make absolutely everything into
602 // span. What I think will work is to check if we're about to write "div" and,
603 // if so, try to close fonts, etc. 
604 // There are probably limits to how well we can do here, though, and we will
605 // have to rely upon users not putting footnotes inside noun-type insets.
606 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
607                                   XHTMLOptions opts) const
608 {
609         // we will always want to output all our paragraphs when we are
610         // called this way.
611         OutputParams runparams = rp;
612         runparams.par_begin = 0;
613         runparams.par_end = text().paragraphs().size();
614         
615         if (undefined()) {
616                 xhtmlParagraphs(text_, buffer(), xs, runparams);
617                 return docstring();
618         }
619
620         InsetLayout const & il = getLayout();
621         if (opts & WriteOuterTag)
622                 xs << html::StartTag(il.htmltag(), il.htmlattr());
623
624         if ((opts & WriteLabel) && !il.counter().empty()) {
625                 BufferParams const & bp = buffer().masterBuffer()->params();
626                 Counters & cntrs = bp.documentClass().counters();
627                 cntrs.step(il.counter(), OutputUpdate);
628                 // FIXME: translate to paragraph language
629                 if (!il.htmllabel().empty()) {
630                         docstring const lbl = 
631                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
632                         // FIXME is this check necessary?
633                         if (!lbl.empty()) {
634                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
635                                 xs << lbl;
636                                 xs << html::EndTag(il.htmllabeltag());
637                         }
638                 }
639         }
640
641         if (opts & WriteInnerTag)
642                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
643
644         // we will eventually lose information about the containing inset
645         if (!allowMultiPar() || opts == JustText)
646                 runparams.html_make_pars = false;
647         if (il.isPassThru())
648                 runparams.pass_thru = true;
649
650         xhtmlParagraphs(text_, buffer(), xs, runparams);
651
652         if (opts & WriteInnerTag)
653                 xs << html::EndTag(il.htmlinnertag());
654
655         if (opts & WriteOuterTag)
656                 xs << html::EndTag(il.htmltag());
657
658         return docstring();
659 }
660
661 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
662                         bool const post) const
663 {
664         OutputParams runparams = runparams_in;
665         runparams.local_font =
666                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
667         if (isPassThru())
668                 runparams.pass_thru = true;
669         if (post)
670                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().postcommandargs(), "post:");
671         else
672                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().latexargs());
673 }
674
675
676 void InsetText::cursorPos(BufferView const & bv,
677                 CursorSlice const & sl, bool boundary, int & x, int & y) const
678 {
679         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
680         y = bv.textMetrics(&text_).cursorY(sl, boundary);
681 }
682
683
684 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
685 {
686         clear();
687         Paragraph & first = paragraphs().front();
688         for (unsigned int i = 0; i < data.length(); ++i)
689                 first.insertChar(i, data[i], font, trackChanges);
690 }
691
692
693 void InsetText::setDrawFrame(bool flag)
694 {
695         drawFrame_ = flag;
696 }
697
698
699 ColorCode InsetText::frameColor() const
700 {
701         return frame_color_;
702 }
703
704
705 void InsetText::setFrameColor(ColorCode col)
706 {
707         frame_color_ = col;
708 }
709
710
711 void InsetText::appendParagraphs(ParagraphList & plist)
712 {
713         // There is little we can do here to keep track of changes.
714         // As of 2006/10/20, appendParagraphs is used exclusively by
715         // LyXTabular::setMultiColumn. In this context, the paragraph break
716         // is lost irreversibly and the appended text doesn't really change
717
718         ParagraphList & pl = paragraphs();
719
720         ParagraphList::iterator pit = plist.begin();
721         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
722         ++pit;
723         mergeParagraph(buffer().params(), pl,
724                        distance(pl.begin(), ins) - 1);
725
726         for_each(pit, plist.end(),
727                  bind(&ParagraphList::push_back, ref(pl), _1));
728 }
729
730
731 void InsetText::addPreview(DocIterator const & text_inset_pos,
732         PreviewLoader & loader) const
733 {
734         ParagraphList::const_iterator pit = paragraphs().begin();
735         ParagraphList::const_iterator pend = paragraphs().end();
736         int pidx = 0;
737
738         DocIterator inset_pos = text_inset_pos;
739         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
740
741         for (; pit != pend; ++pit, ++pidx) {
742                 InsetList::const_iterator it  = pit->insetList().begin();
743                 InsetList::const_iterator end = pit->insetList().end();
744                 inset_pos.pit() = pidx;
745                 for (; it != end; ++it) {
746                         inset_pos.pos() = it->pos;
747                         it->inset->addPreview(inset_pos, loader);
748                 }
749         }
750 }
751
752
753 ParagraphList const & InsetText::paragraphs() const
754 {
755         return text_.paragraphs();
756 }
757
758
759 ParagraphList & InsetText::paragraphs()
760 {
761         return text_.paragraphs();
762 }
763
764
765 bool InsetText::insetAllowed(InsetCode code) const
766 {
767         switch (code) {
768         // Arguments are also allowed in PassThru insets
769         case ARG_CODE:
770                 return true;
771         default:
772                 return !isPassThru();
773         }
774 }
775
776
777 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
778 {
779         ParIterator it2 = it;
780         it2.forwardPos();
781         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
782         if (producesOutput()) {
783                 InsetLayout const & il = getLayout();
784                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
785                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
786                 if (save_layouts) {
787                         // LYXERR0("Entering " << name());
788                         cnt.clearLastLayout();
789                         // FIXME cnt.saveLastCounter()?
790                 }
791                 buffer().updateBuffer(it2, utype);
792                 if (save_layouts) {
793                         // LYXERR0("Exiting " << name());
794                         cnt.restoreLastLayout();
795                         // FIXME cnt.restoreLastCounter()?
796                 }
797         } else {
798                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
799                 // Note that we do not need to call:
800                 //      tclass.counters().clearLastLayout()
801                 // since we are saving and restoring the existing counters, etc.
802                 Counters const savecnt = tclass.counters();
803                 tclass.counters().reset();
804                 // we need float information even in note insets (#9760)
805                 tclass.counters().current_float(savecnt.current_float());
806                 tclass.counters().isSubfloat(savecnt.isSubfloat());
807                 buffer().updateBuffer(it2, utype);
808                 tclass.counters() = savecnt;
809         }
810 }
811
812
813 void InsetText::toString(odocstream & os) const
814 {
815         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
816 }
817
818
819 void InsetText::forOutliner(docstring & os, size_t const maxlen,
820                                                         bool const shorten) const
821 {
822         if (!getLayout().isInToc())
823                 return;
824         text().forOutliner(os, maxlen, shorten);
825 }
826
827
828 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
829                                                  UpdateType utype) const
830 {
831         DocIterator dit = cdit;
832         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
833         iterateForToc(dit, output_active, utype);
834 }
835
836
837 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
838                                                           UpdateType utype) const
839 {
840         DocIterator dit = cdit;
841         // This also ensures that any document has a table of contents
842         shared_ptr<Toc> toc = buffer().tocBackend().toc("tableofcontents");
843
844         BufferParams const & bufparams = buffer_->params();
845         int const min_toclevel = bufparams.documentClass().min_toclevel();
846         // we really should have done this before we got here, but it
847         // can't hurt too much to do it again
848         bool const doing_output = output_active && producesOutput();
849
850         // For each paragraph, traverse its insets and let them add
851         // their toc items
852         ParagraphList const & pars = paragraphs();
853         pit_type pend = paragraphs().size();
854         for (pit_type pit = 0; pit != pend; ++pit) {
855                 Paragraph const & par = pars[pit];
856                 dit.pit() = pit;
857                 // if we find an optarg, we'll save it for use later.
858                 InsetText const * arginset = 0;
859                 InsetList::const_iterator it  = par.insetList().begin();
860                 InsetList::const_iterator end = par.insetList().end();
861                 for (; it != end; ++it) {
862                         Inset & inset = *it->inset;
863                         dit.pos() = it->pos;
864                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
865                         inset.addToToc(dit, doing_output, utype);
866                         if (inset.lyxCode() == ARG_CODE)
867                                 arginset = inset.asInsetText();
868                 }
869                 // now the toc entry for the paragraph
870                 int const toclevel = text().getTocLevel(pit);
871                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
872                         // insert this into the table of contents
873                         docstring tocstring;
874                         int const length = (doing_output && utype == OutputUpdate) ?
875                                 INT_MAX : TOC_ENTRY_LENGTH;
876                         if (arginset) {
877                                 tocstring = par.labelString();
878                                 if (!tocstring.empty())
879                                         tocstring += ' ';
880                                 arginset->text().forOutliner(tocstring, length);
881                         } else
882                                 par.forOutliner(tocstring, length);
883                         dit.pos() = 0;
884                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
885                                                tocstring, doing_output));
886                 }
887
888                 // And now the list of changes.
889                 par.addChangesToToc(dit, buffer(), doing_output);
890         }
891 }
892
893
894 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
895 {
896         if (buffer().isClean())
897                 return Inset::notifyCursorLeaves(old, cur);
898         
899         // find text inset in old cursor
900         Cursor insetCur = old;
901         int scriptSlice = insetCur.find(this);
902         // we can try to continue here. returning true means
903         // the cursor is "now" invalid. which it was.
904         LASSERT(scriptSlice != -1, return true);
905         insetCur.cutOff(scriptSlice);
906         LASSERT(&insetCur.inset() == this, return true);
907         
908         // update the old paragraph's words
909         insetCur.paragraph().updateWords();
910         
911         return Inset::notifyCursorLeaves(old, cur);
912 }
913
914
915 bool InsetText::completionSupported(Cursor const & cur) const
916 {
917         //LASSERT(&cur.bv().cursor().inset() == this, return false);
918         return text_.completionSupported(cur);
919 }
920
921
922 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
923 {
924         return completionSupported(cur);
925 }
926
927
928 bool InsetText::automaticInlineCompletion() const
929 {
930         return lyxrc.completion_inline_text;
931 }
932
933
934 bool InsetText::automaticPopupCompletion() const
935 {
936         return lyxrc.completion_popup_text;
937 }
938
939
940 bool InsetText::showCompletionCursor() const
941 {
942         return lyxrc.completion_cursor_text;
943 }
944
945
946 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
947 {
948         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
949 }
950
951
952 docstring InsetText::completionPrefix(Cursor const & cur) const
953 {
954         if (!completionSupported(cur))
955                 return docstring();
956         return text_.completionPrefix(cur);
957 }
958
959
960 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
961         bool finished)
962 {
963         if (!completionSupported(cur))
964                 return false;
965
966         return text_.insertCompletion(cur, s, finished);
967 }
968
969
970 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
971         Dimension & dim) const
972 {
973         TextMetrics const & tm = cur.bv().textMetrics(&text_);
974         tm.completionPosAndDim(cur, x, y, dim);
975 }
976
977
978 string InsetText::contextMenu(BufferView const &, int, int) const
979 {
980         string context_menu = contextMenuName();
981         if (context_menu != InsetText::contextMenuName())
982                 context_menu += ";" + InsetText::contextMenuName(); 
983         return context_menu;
984 }
985
986
987 string InsetText::contextMenuName() const
988 {
989         return "context-edit";
990 }
991
992
993 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
994 {
995         OutputParams rp(&buffer().params().encoding());
996         rp.for_tooltip = true;
997         odocstringstream oss;
998         oss << prefix;
999
1000         ParagraphList::const_iterator beg = paragraphs().begin();
1001         ParagraphList::const_iterator end = paragraphs().end();
1002         ParagraphList::const_iterator it = beg;
1003         bool ref_printed = false;
1004
1005         for (; it != end; ++it) {
1006                 if (it != beg)
1007                         oss << '\n';
1008                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1009                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1010                         break;
1011         }
1012         docstring str = oss.str();
1013         support::truncateWithEllipsis(str, len);
1014         return str;
1015 }
1016
1017
1018 InsetCaption const * InsetText::getCaptionInset() const
1019 {
1020         ParagraphList::const_iterator pit = paragraphs().begin();
1021         for (; pit != paragraphs().end(); ++pit) {
1022                 InsetList::const_iterator it = pit->insetList().begin();
1023                 for (; it != pit->insetList().end(); ++it) {
1024                         Inset & inset = *it->inset;
1025                         if (inset.lyxCode() == CAPTION_CODE) {
1026                                 InsetCaption const * ins =
1027                                         static_cast<InsetCaption const *>(it->inset);
1028                                 return ins;
1029                         }
1030                 }
1031         }
1032         return 0;
1033 }
1034
1035
1036 docstring InsetText::getCaptionText(OutputParams const & runparams) const
1037 {
1038         InsetCaption const * ins = getCaptionInset();
1039         if (ins == 0)
1040                 return docstring();
1041
1042         odocstringstream ods;
1043         ins->getCaptionAsPlaintext(ods, runparams);
1044         return ods.str();
1045 }
1046
1047
1048 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
1049 {
1050         InsetCaption const * ins = getCaptionInset();
1051         if (ins == 0)
1052                 return docstring();
1053
1054         odocstringstream ods;
1055         XHTMLStream xs(ods);
1056         docstring def = ins->getCaptionAsHTML(xs, runparams);
1057         if (!def.empty())
1058                 // should already have been escaped
1059                 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
1060         return ods.str();
1061 }
1062
1063
1064 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1065 {
1066         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1067 }
1068
1069 } // namespace lyx