]> 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 "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                 xs.startDivision(false);
617                 xhtmlParagraphs(text_, buffer(), xs, runparams);
618                 xs.endDivision();
619                 return docstring();
620         }
621
622         InsetLayout const & il = getLayout();
623         if (opts & WriteOuterTag)
624                 xs << html::StartTag(il.htmltag(), il.htmlattr());
625
626         if ((opts & WriteLabel) && !il.counter().empty()) {
627                 BufferParams const & bp = buffer().masterBuffer()->params();
628                 Counters & cntrs = bp.documentClass().counters();
629                 cntrs.step(il.counter(), OutputUpdate);
630                 // FIXME: translate to paragraph language
631                 if (!il.htmllabel().empty()) {
632                         docstring const lbl = 
633                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
634                         // FIXME is this check necessary?
635                         if (!lbl.empty()) {
636                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
637                                 xs << lbl;
638                                 xs << html::EndTag(il.htmllabeltag());
639                         }
640                 }
641         }
642
643         if (opts & WriteInnerTag)
644                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
645
646         // we will eventually lose information about the containing inset
647         if (!allowMultiPar() || opts == JustText)
648                 runparams.html_make_pars = false;
649         if (il.isPassThru())
650                 runparams.pass_thru = true;
651
652         xs.startDivision(false);
653         xhtmlParagraphs(text_, buffer(), xs, runparams);
654         xs.endDivision();
655
656         if (opts & WriteInnerTag)
657                 xs << html::EndTag(il.htmlinnertag());
658
659         if (opts & WriteOuterTag)
660                 xs << html::EndTag(il.htmltag());
661
662         return docstring();
663 }
664
665 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
666                         bool const post) const
667 {
668         OutputParams runparams = runparams_in;
669         runparams.local_font =
670                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
671         if (isPassThru())
672                 runparams.pass_thru = true;
673         if (post)
674                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().postcommandargs(), "post:");
675         else
676                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().latexargs());
677 }
678
679
680 void InsetText::cursorPos(BufferView const & bv,
681                 CursorSlice const & sl, bool boundary, int & x, int & y) const
682 {
683         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
684         y = bv.textMetrics(&text_).cursorY(sl, boundary);
685 }
686
687
688 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
689 {
690         clear();
691         Paragraph & first = paragraphs().front();
692         for (unsigned int i = 0; i < data.length(); ++i)
693                 first.insertChar(i, data[i], font, trackChanges);
694 }
695
696
697 void InsetText::setDrawFrame(bool flag)
698 {
699         drawFrame_ = flag;
700 }
701
702
703 ColorCode InsetText::frameColor() const
704 {
705         return frame_color_;
706 }
707
708
709 void InsetText::setFrameColor(ColorCode col)
710 {
711         frame_color_ = col;
712 }
713
714
715 void InsetText::appendParagraphs(ParagraphList & plist)
716 {
717         // There is little we can do here to keep track of changes.
718         // As of 2006/10/20, appendParagraphs is used exclusively by
719         // LyXTabular::setMultiColumn. In this context, the paragraph break
720         // is lost irreversibly and the appended text doesn't really change
721
722         ParagraphList & pl = paragraphs();
723
724         ParagraphList::iterator pit = plist.begin();
725         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
726         ++pit;
727         mergeParagraph(buffer().params(), pl,
728                        distance(pl.begin(), ins) - 1);
729
730         for_each(pit, plist.end(),
731                  bind(&ParagraphList::push_back, ref(pl), _1));
732 }
733
734
735 void InsetText::addPreview(DocIterator const & text_inset_pos,
736         PreviewLoader & loader) const
737 {
738         ParagraphList::const_iterator pit = paragraphs().begin();
739         ParagraphList::const_iterator pend = paragraphs().end();
740         int pidx = 0;
741
742         DocIterator inset_pos = text_inset_pos;
743         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
744
745         for (; pit != pend; ++pit, ++pidx) {
746                 InsetList::const_iterator it  = pit->insetList().begin();
747                 InsetList::const_iterator end = pit->insetList().end();
748                 inset_pos.pit() = pidx;
749                 for (; it != end; ++it) {
750                         inset_pos.pos() = it->pos;
751                         it->inset->addPreview(inset_pos, loader);
752                 }
753         }
754 }
755
756
757 ParagraphList const & InsetText::paragraphs() const
758 {
759         return text_.paragraphs();
760 }
761
762
763 ParagraphList & InsetText::paragraphs()
764 {
765         return text_.paragraphs();
766 }
767
768
769 bool InsetText::insetAllowed(InsetCode code) const
770 {
771         switch (code) {
772         // Arguments are also allowed in PassThru insets
773         case ARG_CODE:
774                 return true;
775         default:
776                 return !isPassThru();
777         }
778 }
779
780
781 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
782 {
783         ParIterator it2 = it;
784         it2.forwardPos();
785         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
786         if (producesOutput()) {
787                 InsetLayout const & il = getLayout();
788                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
789                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
790                 if (save_layouts) {
791                         // LYXERR0("Entering " << name());
792                         cnt.clearLastLayout();
793                         // FIXME cnt.saveLastCounter()?
794                 }
795                 buffer().updateBuffer(it2, utype);
796                 if (save_layouts) {
797                         // LYXERR0("Exiting " << name());
798                         cnt.restoreLastLayout();
799                         // FIXME cnt.restoreLastCounter()?
800                 }
801         } else {
802                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
803                 // Note that we do not need to call:
804                 //      tclass.counters().clearLastLayout()
805                 // since we are saving and restoring the existing counters, etc.
806                 Counters const savecnt = tclass.counters();
807                 tclass.counters().reset();
808                 // we need float information even in note insets (#9760)
809                 tclass.counters().current_float(savecnt.current_float());
810                 tclass.counters().isSubfloat(savecnt.isSubfloat());
811                 buffer().updateBuffer(it2, utype);
812                 tclass.counters() = savecnt;
813         }
814 }
815
816
817 void InsetText::toString(odocstream & os) const
818 {
819         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
820 }
821
822
823 void InsetText::forOutliner(docstring & os, size_t const maxlen,
824                                                         bool const shorten) const
825 {
826         if (!getLayout().isInToc())
827                 return;
828         text().forOutliner(os, maxlen, shorten);
829 }
830
831
832 void InsetText::addToToc(DocIterator const & cdit, bool output_active,
833                                                  UpdateType utype) const
834 {
835         DocIterator dit = cdit;
836         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
837         iterateForToc(dit, output_active, utype);
838 }
839
840
841 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active,
842                                                           UpdateType utype) const
843 {
844         DocIterator dit = cdit;
845         // This also ensures that any document has a table of contents
846         shared_ptr<Toc> toc = buffer().tocBackend().toc("tableofcontents");
847
848         BufferParams const & bufparams = buffer_->params();
849         int const min_toclevel = bufparams.documentClass().min_toclevel();
850         // we really should have done this before we got here, but it
851         // can't hurt too much to do it again
852         bool const doing_output = output_active && producesOutput();
853
854         // For each paragraph, traverse its insets and let them add
855         // their toc items
856         ParagraphList const & pars = paragraphs();
857         pit_type pend = paragraphs().size();
858         for (pit_type pit = 0; pit != pend; ++pit) {
859                 Paragraph const & par = pars[pit];
860                 dit.pit() = pit;
861                 // if we find an optarg, we'll save it for use later.
862                 InsetText const * arginset = 0;
863                 InsetList::const_iterator it  = par.insetList().begin();
864                 InsetList::const_iterator end = par.insetList().end();
865                 for (; it != end; ++it) {
866                         Inset & inset = *it->inset;
867                         dit.pos() = it->pos;
868                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
869                         inset.addToToc(dit, doing_output, utype);
870                         if (inset.lyxCode() == ARG_CODE)
871                                 arginset = inset.asInsetText();
872                 }
873                 // now the toc entry for the paragraph
874                 int const toclevel = text().getTocLevel(pit);
875                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
876                         // insert this into the table of contents
877                         docstring tocstring;
878                         int const length = (doing_output && utype == OutputUpdate) ?
879                                 INT_MAX : TOC_ENTRY_LENGTH;
880                         if (arginset) {
881                                 tocstring = par.labelString();
882                                 if (!tocstring.empty())
883                                         tocstring += ' ';
884                                 arginset->text().forOutliner(tocstring, length);
885                         } else
886                                 par.forOutliner(tocstring, length);
887                         dit.pos() = 0;
888                         toc->push_back(TocItem(dit, toclevel - min_toclevel,
889                                                tocstring, doing_output));
890                 }
891
892                 // And now the list of changes.
893                 par.addChangesToToc(dit, buffer(), doing_output);
894         }
895 }
896
897
898 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
899 {
900         if (buffer().isClean())
901                 return Inset::notifyCursorLeaves(old, cur);
902         
903         // find text inset in old cursor
904         Cursor insetCur = old;
905         int scriptSlice = insetCur.find(this);
906         // we can try to continue here. returning true means
907         // the cursor is "now" invalid. which it was.
908         LASSERT(scriptSlice != -1, return true);
909         insetCur.cutOff(scriptSlice);
910         LASSERT(&insetCur.inset() == this, return true);
911         
912         // update the old paragraph's words
913         insetCur.paragraph().updateWords();
914         
915         return Inset::notifyCursorLeaves(old, cur);
916 }
917
918
919 bool InsetText::completionSupported(Cursor const & cur) const
920 {
921         //LASSERT(&cur.bv().cursor().inset() == this, return false);
922         return text_.completionSupported(cur);
923 }
924
925
926 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
927 {
928         return completionSupported(cur);
929 }
930
931
932 bool InsetText::automaticInlineCompletion() const
933 {
934         return lyxrc.completion_inline_text;
935 }
936
937
938 bool InsetText::automaticPopupCompletion() const
939 {
940         return lyxrc.completion_popup_text;
941 }
942
943
944 bool InsetText::showCompletionCursor() const
945 {
946         return lyxrc.completion_cursor_text;
947 }
948
949
950 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
951 {
952         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
953 }
954
955
956 docstring InsetText::completionPrefix(Cursor const & cur) const
957 {
958         if (!completionSupported(cur))
959                 return docstring();
960         return text_.completionPrefix(cur);
961 }
962
963
964 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
965         bool finished)
966 {
967         if (!completionSupported(cur))
968                 return false;
969
970         return text_.insertCompletion(cur, s, finished);
971 }
972
973
974 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
975         Dimension & dim) const
976 {
977         TextMetrics const & tm = cur.bv().textMetrics(&text_);
978         tm.completionPosAndDim(cur, x, y, dim);
979 }
980
981
982 string InsetText::contextMenu(BufferView const &, int, int) const
983 {
984         string context_menu = contextMenuName();
985         if (context_menu != InsetText::contextMenuName())
986                 context_menu += ";" + InsetText::contextMenuName(); 
987         return context_menu;
988 }
989
990
991 string InsetText::contextMenuName() const
992 {
993         return "context-edit";
994 }
995
996
997 docstring InsetText::toolTipText(docstring prefix, size_t const len) const
998 {
999         OutputParams rp(&buffer().params().encoding());
1000         rp.for_tooltip = true;
1001         odocstringstream oss;
1002         oss << prefix;
1003
1004         ParagraphList::const_iterator beg = paragraphs().begin();
1005         ParagraphList::const_iterator end = paragraphs().end();
1006         ParagraphList::const_iterator it = beg;
1007         bool ref_printed = false;
1008
1009         for (; it != end; ++it) {
1010                 if (it != beg)
1011                         oss << '\n';
1012                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, len);
1013                 if (oss.tellp() >= 0 && size_t(oss.tellp()) > len)
1014                         break;
1015         }
1016         docstring str = oss.str();
1017         support::truncateWithEllipsis(str, len);
1018         return str;
1019 }
1020
1021
1022 InsetCaption const * InsetText::getCaptionInset() const
1023 {
1024         ParagraphList::const_iterator pit = paragraphs().begin();
1025         for (; pit != paragraphs().end(); ++pit) {
1026                 InsetList::const_iterator it = pit->insetList().begin();
1027                 for (; it != pit->insetList().end(); ++it) {
1028                         Inset & inset = *it->inset;
1029                         if (inset.lyxCode() == CAPTION_CODE) {
1030                                 InsetCaption const * ins =
1031                                         static_cast<InsetCaption const *>(it->inset);
1032                                 return ins;
1033                         }
1034                 }
1035         }
1036         return 0;
1037 }
1038
1039
1040 docstring InsetText::getCaptionText(OutputParams const & runparams) const
1041 {
1042         InsetCaption const * ins = getCaptionInset();
1043         if (ins == 0)
1044                 return docstring();
1045
1046         odocstringstream ods;
1047         ins->getCaptionAsPlaintext(ods, runparams);
1048         return ods.str();
1049 }
1050
1051
1052 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
1053 {
1054         InsetCaption const * ins = getCaptionInset();
1055         if (ins == 0)
1056                 return docstring();
1057
1058         odocstringstream ods;
1059         XHTMLStream xs(ods);
1060         docstring def = ins->getCaptionAsHTML(xs, runparams);
1061         if (!def.empty())
1062                 // should already have been escaped
1063                 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
1064         return ods.str();
1065 }
1066
1067
1068 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1069 {
1070         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1071 }
1072
1073 } // namespace lyx