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