]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Improve the check for multiple paragraphs in Text::insertStringAsLine.
[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         LBUFERR(!pars.empty());
129
130         // This is a gross hack...
131         Layout const & old_layout = pars.begin()->layout();
132
133         pars.clear();
134         pars.push_back(Paragraph());
135         pars.begin()->setInsetOwner(this);
136         pars.begin()->setLayout(old_layout);
137 }
138
139
140 Dimension const InsetText::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.finishUndo();
255 }
256
257
258 Inset * InsetText::editXY(Cursor & cur, int x, int y)
259 {
260         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
261 }
262
263
264 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
265 {
266         LYXERR(Debug::ACTION, "InsetText::doDispatch(): cmd: " << cmd);
267
268         // See bug #9042, for instance.
269         if (isPassThru() && lyxCode() != ARG_CODE) {
270                 // Force any new text to latex_language FIXME: This
271                 // should only be necessary in constructor, but new
272                 // paragraphs that are created by pressing enter at
273                 // the start of an existing paragraph get the buffer
274                 // language and not latex_language, so we take this
275                 // brute force approach.
276                 cur.current_font.setLanguage(latex_language);
277                 cur.real_current_font.setLanguage(latex_language);
278         }
279
280         switch (cmd.action()) {
281         case LFUN_PASTE:
282         case LFUN_CLIPBOARD_PASTE:
283         case LFUN_SELECTION_PASTE:
284         case LFUN_PRIMARY_SELECTION_PASTE:
285                 text_.dispatch(cur, cmd);
286                 // If we we can only store plain text, we must reset all
287                 // attributes.
288                 // FIXME: Change only the pasted paragraphs
289                 fixParagraphsFont();
290                 break;
291
292         case LFUN_INSET_DISSOLVE: {
293                 bool const main_inset = &buffer().inset() == this;
294                 bool const target_inset = cmd.argument().empty() 
295                         || cmd.getArg(0) == insetName(lyxCode());
296                 bool const one_cell = nargs() == 1;
297
298                 if (!main_inset && target_inset && one_cell) {
299                         // Text::dissolveInset assumes that the cursor
300                         // is inside the Inset.
301                         if (&cur.inset() != this)
302                                 cur.pushBackward(*this);
303                         cur.beginUndoGroup();
304                         text_.dispatch(cur, cmd);
305                         cur.endUndoGroup();
306                 } else
307                         cur.undispatched();
308                 break;
309         }
310
311         default:
312                 text_.dispatch(cur, cmd);
313         }
314         
315         if (!cur.result().dispatched())
316                 Inset::doDispatch(cur, cmd);
317 }
318
319
320 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
321         FuncStatus & status) const
322 {
323         switch (cmd.action()) {
324         case LFUN_INSET_DISSOLVE: {
325                 bool const main_inset = &buffer().inset() == this;
326                 bool const target_inset = cmd.argument().empty() 
327                         || cmd.getArg(0) == insetName(lyxCode());
328                 bool const one_cell = nargs() == 1;
329
330                 if (target_inset)
331                         status.setEnabled(!main_inset && one_cell);
332                 return target_inset;
333         }
334
335         case LFUN_ARGUMENT_INSERT: {
336                 string const arg = cmd.getArg(0);
337                 if (arg.empty()) {
338                         status.setEnabled(false);
339                         return true;
340                 }
341                 if (&buffer().inset() == this || !cur.paragraph().layout().args().empty())
342                         return text_.getStatus(cur, cmd, status);
343
344                 Layout::LaTeXArgMap args = getLayout().args();
345                 Layout::LaTeXArgMap::const_iterator const lait = args.find(arg);
346                 if (lait != args.end()) {
347                         status.setEnabled(true);
348                         ParagraphList::const_iterator pit = paragraphs().begin();
349                         for (; pit != paragraphs().end(); ++pit) {
350                                 InsetList::const_iterator it = pit->insetList().begin();
351                                 InsetList::const_iterator end = pit->insetList().end();
352                                 for (; it != end; ++it) {
353                                         if (it->inset->lyxCode() == ARG_CODE) {
354                                                 InsetArgument const * ins =
355                                                         static_cast<InsetArgument const *>(it->inset);
356                                                 if (ins->name() == arg) {
357                                                         // we have this already
358                                                         status.setEnabled(false);
359                                                         return true;
360                                                 }
361                                         }
362                                 }
363                         }
364                 } else
365                         status.setEnabled(false);
366                 return true;
367         }
368
369         default:
370                 // Dispatch only to text_ if the cursor is inside
371                 // the text_. It is not for context menus (bug 5797).
372                 bool ret = false;
373                 if (cur.text() == &text_)
374                         ret = text_.getStatus(cur, cmd, status);
375                 
376                 if (!ret)
377                         ret = Inset::getStatus(cur, cmd, status);
378                 return ret;
379         }
380 }
381
382
383 void InsetText::fixParagraphsFont()
384 {
385         Font font(inherit_font, buffer().params().language);
386         font.setLanguage(latex_language);
387         ParagraphList::iterator par = paragraphs().begin();
388         ParagraphList::iterator const end = paragraphs().end();
389         while (par != end) {
390                 if (par->isPassThru())
391                         par->resetFonts(font);
392                 if (!par->allowParagraphCustomization())
393                         par->params().clear();
394                 ++par;
395         }
396 }
397
398
399 void InsetText::setChange(Change const & change)
400 {
401         ParagraphList::iterator pit = paragraphs().begin();
402         ParagraphList::iterator end = paragraphs().end();
403         for (; pit != end; ++pit) {
404                 pit->setChange(change);
405         }
406 }
407
408
409 void InsetText::acceptChanges()
410 {
411         text_.acceptChanges();
412 }
413
414
415 void InsetText::rejectChanges()
416 {
417         text_.rejectChanges();
418 }
419
420
421 void InsetText::validate(LaTeXFeatures & features) const
422 {
423         features.useInsetLayout(getLayout());
424         for_each(paragraphs().begin(), paragraphs().end(),
425                  bind(&Paragraph::validate, _1, ref(features)));
426 }
427
428
429 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
430 {
431         // This implements the standard way of handling the LaTeX
432         // output of a text inset, either a command or an
433         // environment. Standard collapsable insets should not
434         // redefine this, non-standard ones may call this.
435         InsetLayout const & il = getLayout();
436         if (il.forceOwnlines())
437                 os << breakln;
438         if (!il.latexname().empty()) {
439                 if (il.latextype() == InsetLayout::COMMAND) {
440                         // FIXME UNICODE
441                         // FIXME \protect should only be used for fragile
442                         //    commands, but we do not provide this information yet.
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()) << "}" << breakln;
503                         if (!il.isDisplay())
504                                 os.protectSpace(true);
505                 }
506         }
507         if (il.forceOwnlines())
508                 os << breakln;
509 }
510
511
512 int InsetText::plaintext(odocstringstream & os,
513         OutputParams const & runparams, size_t max_length) const
514 {
515         ParagraphList::const_iterator beg = paragraphs().begin();
516         ParagraphList::const_iterator end = paragraphs().end();
517         ParagraphList::const_iterator it = beg;
518         bool ref_printed = false;
519         int len = 0;
520         for (; it != end; ++it) {
521                 if (it != beg) {
522                         os << '\n';
523                         if (runparams.linelen > 0)
524                                 os << '\n';
525                 }
526                 odocstringstream oss;
527                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed, max_length);
528                 docstring const str = oss.str();
529                 os << str;
530                 // FIXME: len is not computed fully correctly; in principle,
531                 // we have to count the characters after the last '\n'
532                 len = str.size();
533                 if (os.str().size() >= max_length)
534                         break;
535         }
536
537         return len;
538 }
539
540
541 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
542 {
543         ParagraphList::const_iterator const beg = paragraphs().begin();
544
545         if (!undefined())
546                 sgml::openTag(os, getLayout().latexname(),
547                               beg->getID(buffer(), runparams) + getLayout().latexparam());
548
549         docbookParagraphs(text_, buffer(), os, runparams);
550
551         if (!undefined())
552                 sgml::closeTag(os, getLayout().latexname());
553
554         return 0;
555 }
556
557
558 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
559 {
560         return insetAsXHTML(xs, runparams, WriteEverything);
561 }
562
563
564 // FIXME XHTML
565 // There are cases where we may need to close open fonts and such
566 // and then re-open them when we are done. This would be the case, e.g.,
567 // if we were otherwise about to write:
568 //              <em>word <div class='foot'>footnote text.</div> emph</em>
569 // The problem isn't so much that the footnote text will get emphasized:
570 // we can handle that with CSS. The problem is that this is invalid XHTML.
571 // One solution would be to make the footnote <span>, but the problem is
572 // completely general, and so we'd have to make absolutely everything into
573 // span. What I think will work is to check if we're about to write "div" and,
574 // if so, try to close fonts, etc. 
575 // There are probably limits to how well we can do here, though, and we will
576 // have to rely upon users not putting footnotes inside noun-type insets.
577 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
578                                   XHTMLOptions opts) const
579 {
580         // we will always want to output all our paragraphs when we are
581         // called this way.
582         OutputParams runparams = rp;
583         runparams.par_begin = 0;
584         runparams.par_end = text().paragraphs().size();
585         
586         if (undefined()) {
587                 xhtmlParagraphs(text_, buffer(), xs, runparams);
588                 return docstring();
589         }
590
591         InsetLayout const & il = getLayout();
592         if (opts & WriteOuterTag)
593                 xs << html::StartTag(il.htmltag(), il.htmlattr());
594
595         if ((opts & WriteLabel) && !il.counter().empty()) {
596                 BufferParams const & bp = buffer().masterBuffer()->params();
597                 Counters & cntrs = bp.documentClass().counters();
598                 cntrs.step(il.counter(), OutputUpdate);
599                 // FIXME: translate to paragraph language
600                 if (!il.htmllabel().empty()) {
601                         docstring const lbl = 
602                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
603                         // FIXME is this check necessary?
604                         if (!lbl.empty()) {
605                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
606                                 xs << lbl;
607                                 xs << html::EndTag(il.htmllabeltag());
608                         }
609                 }
610         }
611
612         if (opts & WriteInnerTag)
613                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
614
615         // we will eventually lose information about the containing inset
616         if (!allowMultiPar() || opts == JustText)
617                 runparams.html_make_pars = false;
618         if (il.isPassThru())
619                 runparams.pass_thru = true;
620
621         xhtmlParagraphs(text_, buffer(), xs, runparams);
622
623         if (opts & WriteInnerTag)
624                 xs << html::EndTag(il.htmlinnertag());
625
626         if (opts & WriteOuterTag)
627                 xs << html::EndTag(il.htmltag());
628
629         return docstring();
630 }
631
632 void InsetText::getArgs(otexstream & os, OutputParams const & runparams_in,
633                         bool const post) const
634 {
635         OutputParams runparams = runparams_in;
636         runparams.local_font =
637                 &paragraphs()[0].getFirstFontSettings(buffer().masterBuffer()->params());
638         if (isPassThru())
639                 runparams.pass_thru = true;
640         if (post)
641                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().postcommandargs(), "post:");
642         else
643                 latexArgInsets(paragraphs(), paragraphs().begin(), os, runparams, getLayout().latexargs());
644 }
645
646
647 void InsetText::cursorPos(BufferView const & bv,
648                 CursorSlice const & sl, bool boundary, int & x, int & y) const
649 {
650         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
651         y = bv.textMetrics(&text_).cursorY(sl, boundary);
652 }
653
654
655 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
656 {
657         clear();
658         Paragraph & first = paragraphs().front();
659         for (unsigned int i = 0; i < data.length(); ++i)
660                 first.insertChar(i, data[i], font, trackChanges);
661 }
662
663
664 void InsetText::setAutoBreakRows(bool flag)
665 {
666         if (flag == text_.autoBreakRows_)
667                 return;
668
669         text_.autoBreakRows_ = flag;
670         if (flag)
671                 return;
672
673         // remove previously existing newlines
674         ParagraphList::iterator it = paragraphs().begin();
675         ParagraphList::iterator end = paragraphs().end();
676         for (; it != end; ++it)
677                 for (int i = 0; i < it->size(); ++i)
678                         if (it->isNewline(i))
679                                 // do not track the change, because the user
680                                 // is not allowed to revert/reject it
681                                 it->eraseChar(i, false);
682 }
683
684
685 void InsetText::setDrawFrame(bool flag)
686 {
687         drawFrame_ = flag;
688 }
689
690
691 ColorCode InsetText::frameColor() const
692 {
693         return frame_color_;
694 }
695
696
697 void InsetText::setFrameColor(ColorCode col)
698 {
699         frame_color_ = col;
700 }
701
702
703 void InsetText::appendParagraphs(ParagraphList & plist)
704 {
705         // There is little we can do here to keep track of changes.
706         // As of 2006/10/20, appendParagraphs is used exclusively by
707         // LyXTabular::setMultiColumn. In this context, the paragraph break
708         // is lost irreversibly and the appended text doesn't really change
709
710         ParagraphList & pl = paragraphs();
711
712         ParagraphList::iterator pit = plist.begin();
713         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
714         ++pit;
715         mergeParagraph(buffer().params(), pl,
716                        distance(pl.begin(), ins) - 1);
717
718         for_each(pit, plist.end(),
719                  bind(&ParagraphList::push_back, ref(pl), _1));
720 }
721
722
723 void InsetText::addPreview(DocIterator const & text_inset_pos,
724         PreviewLoader & loader) const
725 {
726         ParagraphList::const_iterator pit = paragraphs().begin();
727         ParagraphList::const_iterator pend = paragraphs().end();
728         int pidx = 0;
729
730         DocIterator inset_pos = text_inset_pos;
731         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
732
733         for (; pit != pend; ++pit, ++pidx) {
734                 InsetList::const_iterator it  = pit->insetList().begin();
735                 InsetList::const_iterator end = pit->insetList().end();
736                 inset_pos.pit() = pidx;
737                 for (; it != end; ++it) {
738                         inset_pos.pos() = it->pos;
739                         it->inset->addPreview(inset_pos, loader);
740                 }
741         }
742 }
743
744
745 ParagraphList const & InsetText::paragraphs() const
746 {
747         return text_.paragraphs();
748 }
749
750
751 ParagraphList & InsetText::paragraphs()
752 {
753         return text_.paragraphs();
754 }
755
756
757 bool InsetText::insetAllowed(InsetCode code) const
758 {
759         switch (code) {
760         // Arguments are also allowed in PassThru insets
761         case ARG_CODE:
762                 return true;
763         default:
764                 return !isPassThru();
765         }
766 }
767
768
769 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
770 {
771         ParIterator it2 = it;
772         it2.forwardPos();
773         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
774         if (producesOutput()) {
775                 InsetLayout const & il = getLayout();
776                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
777                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
778                 if (save_layouts) {
779                         // LYXERR0("Entering " << name());
780                         cnt.clearLastLayout();
781                         // FIXME cnt.saveLastCounter()?
782                 }
783                 buffer().updateBuffer(it2, utype);
784                 if (save_layouts) {
785                         // LYXERR0("Exiting " << name());
786                         cnt.restoreLastLayout();
787                         // FIXME cnt.restoreLastCounter()?
788                 }
789         } else {
790                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
791                 // Note that we do not need to call:
792                 //      tclass.counters().clearLastLayout()
793                 // since we are saving and restoring the existing counters, etc.
794                 Counters const savecnt = tclass.counters();
795                 tclass.counters().reset();
796                 buffer().updateBuffer(it2, utype);
797                 tclass.counters() = savecnt;
798         }
799 }
800
801
802 void InsetText::toString(odocstream & os) const
803 {
804         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
805 }
806
807
808 void InsetText::forOutliner(docstring & os, size_t maxlen) const
809 {
810         if (!getLayout().isInToc())
811                 return;
812         text().forOutliner(os, maxlen, false);
813 }
814
815
816 void InsetText::addToToc(DocIterator const & cdit, bool output_active) const
817 {
818         DocIterator dit = cdit;
819         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
820         iterateForToc(dit, output_active);
821 }
822
823
824 void InsetText::iterateForToc(DocIterator const & cdit, bool output_active) const
825 {
826         DocIterator dit = cdit;
827         Toc & toc = buffer().tocBackend().toc("tableofcontents");
828
829         BufferParams const & bufparams = buffer_->params();
830         int const min_toclevel = bufparams.documentClass().min_toclevel();
831         // we really should have done this before we got here, but it
832         // can't hurt too much to do it again
833         bool const doing_output = output_active && producesOutput();
834
835         // For each paragraph, traverse its insets and let them add
836         // their toc items
837         ParagraphList const & pars = paragraphs();
838         pit_type pend = paragraphs().size();
839         for (pit_type pit = 0; pit != pend; ++pit) {
840                 Paragraph const & par = pars[pit];
841                 dit.pit() = pit;
842                 // if we find an optarg, we'll save it for use later.
843                 InsetText const * arginset = 0;
844                 InsetList::const_iterator it  = par.insetList().begin();
845                 InsetList::const_iterator end = par.insetList().end();
846                 for (; it != end; ++it) {
847                         Inset & inset = *it->inset;
848                         dit.pos() = it->pos;
849                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
850                         inset.addToToc(dit, doing_output);
851                         if (inset.lyxCode() == ARG_CODE)
852                                 arginset = inset.asInsetText();
853                 }
854                 // now the toc entry for the paragraph
855                 int const toclevel = text().getTocLevel(pit);
856                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
857                         // insert this into the table of contents
858                         docstring tocstring;
859                         int const length = doing_output ? INT_MAX : TOC_ENTRY_LENGTH;
860                         if (arginset) {
861                                 tocstring = par.labelString();
862                                 if (!tocstring.empty())
863                                         tocstring += ' ';
864                                 arginset->text().forOutliner(tocstring, length);
865                         } else
866                                 par.forOutliner(tocstring, length);
867                         dit.pos() = 0;
868                         toc.push_back(TocItem(dit, toclevel - min_toclevel,
869                                 tocstring, doing_output, tocstring));
870                 }
871                 
872                 // And now the list of changes.
873                 par.addChangesToToc(dit, buffer(), doing_output);
874         }
875 }
876
877
878 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
879 {
880         if (buffer().isClean())
881                 return Inset::notifyCursorLeaves(old, cur);
882         
883         // find text inset in old cursor
884         Cursor insetCur = old;
885         int scriptSlice = insetCur.find(this);
886         // we can try to continue here. returning true means
887         // the cursor is "now" invalid. which it was.
888         LASSERT(scriptSlice != -1, return true);
889         insetCur.cutOff(scriptSlice);
890         LASSERT(&insetCur.inset() == this, return true);
891         
892         // update the old paragraph's words
893         insetCur.paragraph().updateWords();
894         
895         return Inset::notifyCursorLeaves(old, cur);
896 }
897
898
899 bool InsetText::completionSupported(Cursor const & cur) const
900 {
901         //LASSERT(&cur.bv().cursor().inset() == this, return false);
902         return text_.completionSupported(cur);
903 }
904
905
906 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
907 {
908         return completionSupported(cur);
909 }
910
911
912 bool InsetText::automaticInlineCompletion() const
913 {
914         return lyxrc.completion_inline_text;
915 }
916
917
918 bool InsetText::automaticPopupCompletion() const
919 {
920         return lyxrc.completion_popup_text;
921 }
922
923
924 bool InsetText::showCompletionCursor() const
925 {
926         return lyxrc.completion_cursor_text;
927 }
928
929
930 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
931 {
932         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
933 }
934
935
936 docstring InsetText::completionPrefix(Cursor const & cur) const
937 {
938         if (!completionSupported(cur))
939                 return docstring();
940         return text_.completionPrefix(cur);
941 }
942
943
944 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
945         bool finished)
946 {
947         if (!completionSupported(cur))
948                 return false;
949
950         return text_.insertCompletion(cur, s, finished);
951 }
952
953
954 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
955         Dimension & dim) const
956 {
957         TextMetrics const & tm = cur.bv().textMetrics(&text_);
958         tm.completionPosAndDim(cur, x, y, dim);
959 }
960
961
962 string InsetText::contextMenu(BufferView const &, int, int) const
963 {
964         string context_menu = contextMenuName();
965         if (context_menu != InsetText::contextMenuName())
966                 context_menu += ";" + InsetText::contextMenuName(); 
967         return context_menu;
968 }
969
970
971 string InsetText::contextMenuName() const
972 {
973         return "context-edit";
974 }
975
976
977 docstring InsetText::toolTipText(docstring prefix,
978                 size_t numlines, size_t len) const
979 {
980         size_t const max_length = numlines * len;
981         OutputParams rp(&buffer().params().encoding());
982         rp.for_tooltip = true;
983         odocstringstream oss;
984         oss << prefix;
985
986         ParagraphList::const_iterator beg = paragraphs().begin();
987         ParagraphList::const_iterator end = paragraphs().end();
988         ParagraphList::const_iterator it = beg;
989         bool ref_printed = false;
990         docstring str;
991
992         for (; it != end; ++it) {
993                 if (it != beg)
994                         oss << '\n';
995                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed, max_length);
996                 str = oss.str();
997                 if (str.length() >= max_length)
998                         break;
999         }
1000         return support::wrapParas(str, 4, len, numlines);
1001 }
1002
1003
1004 InsetCaption const * InsetText::getCaptionInset() const
1005 {
1006         ParagraphList::const_iterator pit = paragraphs().begin();
1007         for (; pit != paragraphs().end(); ++pit) {
1008                 InsetList::const_iterator it = pit->insetList().begin();
1009                 for (; it != pit->insetList().end(); ++it) {
1010                         Inset & inset = *it->inset;
1011                         if (inset.lyxCode() == CAPTION_CODE) {
1012                                 InsetCaption const * ins =
1013                                         static_cast<InsetCaption const *>(it->inset);
1014                                 return ins;
1015                         }
1016                 }
1017         }
1018         return 0;
1019 }
1020
1021
1022 docstring InsetText::getCaptionText(OutputParams const & runparams) const
1023 {
1024         InsetCaption const * ins = getCaptionInset();
1025         if (ins == 0)
1026                 return docstring();
1027
1028         odocstringstream ods;
1029         ins->getCaptionAsPlaintext(ods, runparams);
1030         return ods.str();
1031 }
1032
1033
1034 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
1035 {
1036         InsetCaption const * ins = getCaptionInset();
1037         if (ins == 0)
1038                 return docstring();
1039
1040         odocstringstream ods;
1041         XHTMLStream xs(ods);
1042         docstring def = ins->getCaptionAsHTML(xs, runparams);
1043         if (!def.empty())
1044                 // should already have been escaped
1045                 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
1046         return ods.str();
1047 }
1048
1049
1050 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1051 {
1052         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1053 }
1054
1055 } // namespace lyx