]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Merge branch 'master' of git.lyx.org:lyx
[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 (getLayout().isPassThru()) {
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().latexargs().empty())
342                         return text_.getStatus(cur, cmd, status);
343                 Layout::LaTeXArgMap args = getLayout().latexargs();
344                 Layout::LaTeXArgMap::const_iterator const lait =
345                                 args.find(convert<unsigned int>(arg));
346                 if (lait != args.end()) {
347                         status.setEnabled(true);
348                         InsetList::const_iterator it = cur.paragraph().insetList().begin();
349                         InsetList::const_iterator end = cur.paragraph().insetList().end();
350                         for (; it != end; ++it) {
351                                 if (it->inset->lyxCode() == ARG_CODE) {
352                                         InsetArgument const * ins =
353                                                 static_cast<InsetArgument const *>(it->inset);
354                                         if (ins->name() == arg) {
355                                                 // we have this already
356                                                 status.setEnabled(false);
357                                                 return true;
358                                         }
359                                 }
360                         }
361                 } else
362                         status.setEnabled(false);
363                 return true;
364         }
365
366         default:
367                 // Dispatch only to text_ if the cursor is inside
368                 // the text_. It is not for context menus (bug 5797).
369                 bool ret = false;
370                 if (cur.text() == &text_)
371                         ret = text_.getStatus(cur, cmd, status);
372                 
373                 if (!ret)
374                         ret = Inset::getStatus(cur, cmd, status);
375                 return ret;
376         }
377 }
378
379
380 void InsetText::fixParagraphsFont()
381 {
382         Font font(inherit_font, buffer().params().language);
383         font.setLanguage(latex_language);
384         ParagraphList::iterator par = paragraphs().begin();
385         ParagraphList::iterator const end = paragraphs().end();
386         while (par != end) {
387                 if (par->isPassThru())
388                         par->resetFonts(font);
389                 if (!par->allowParagraphCustomization())
390                         par->params().clear();
391                 ++par;
392         }
393 }
394
395
396 void InsetText::setChange(Change const & change)
397 {
398         ParagraphList::iterator pit = paragraphs().begin();
399         ParagraphList::iterator end = paragraphs().end();
400         for (; pit != end; ++pit) {
401                 pit->setChange(change);
402         }
403 }
404
405
406 void InsetText::acceptChanges()
407 {
408         text_.acceptChanges();
409 }
410
411
412 void InsetText::rejectChanges()
413 {
414         text_.rejectChanges();
415 }
416
417
418 void InsetText::validate(LaTeXFeatures & features) const
419 {
420         features.useInsetLayout(getLayout());
421         for_each(paragraphs().begin(), paragraphs().end(),
422                  bind(&Paragraph::validate, _1, ref(features)));
423 }
424
425
426 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
427 {
428         // This implements the standard way of handling the LaTeX
429         // output of a text inset, either a command or an
430         // environment. Standard collapsable insets should not
431         // redefine this, non-standard ones may call this.
432         InsetLayout const & il = getLayout();
433         if (!il.latexname().empty()) {
434                 if (il.latextype() == InsetLayout::COMMAND) {
435                         // FIXME UNICODE
436                         if (runparams.moving_arg)
437                                 os << "\\protect";
438                         os << '\\' << from_utf8(il.latexname());
439                         getOptArg(os, runparams);
440                         if (!il.latexparam().empty())
441                                 os << from_utf8(il.latexparam());
442                         os << '{';
443                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
444                         if (il.isDisplay())
445                                 os << breakln;
446                         else
447                                 os << safebreakln;
448                         if (runparams.lastid != -1)
449                                 os.texrow().start(runparams.lastid,
450                                                   runparams.lastpos);
451                         os << "\\begin{" << from_utf8(il.latexname()) << "}";
452                         getOptArg(os, runparams);
453                         if (!il.latexparam().empty())
454                                 os << from_utf8(il.latexparam());
455                         os << '\n';
456                 }
457         } else {
458                 getOptArg(os, runparams);
459                 if (!il.latexparam().empty())
460                         os << from_utf8(il.latexparam());
461         }
462
463         if (!il.leftdelim().empty())
464                 os << il.leftdelim();
465
466         OutputParams rp = runparams;
467         if (il.isPassThru())
468                 rp.pass_thru = true;
469         if (il.isNeedProtect())
470                 rp.moving_arg = true;
471         rp.par_begin = 0;
472         rp.par_end = paragraphs().size();
473
474         // Output the contents of the inset
475         latexParagraphs(buffer(), text_, os, rp);
476         runparams.encoding = rp.encoding;
477
478         if (!il.rightdelim().empty())
479                 os << il.rightdelim();
480
481         if (!il.latexname().empty()) {
482                 if (il.latextype() == InsetLayout::COMMAND) {
483                         os << "}";
484                 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
485                         // A comment environment doesn't need a % before \n\end
486                         if (il.isDisplay() || runparams.inComment)
487                             os << breakln;
488                         else
489                             os << safebreakln;
490                         os << "\\end{" << from_utf8(il.latexname()) << "}\n";
491                         if (!il.isDisplay())
492                                 os.protectSpace(true);
493                 }
494         }
495 }
496
497
498 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
499 {
500         ParagraphList::const_iterator beg = paragraphs().begin();
501         ParagraphList::const_iterator end = paragraphs().end();
502         ParagraphList::const_iterator it = beg;
503         bool ref_printed = false;
504         int len = 0;
505         for (; it != end; ++it) {
506                 if (it != beg) {
507                         os << '\n';
508                         if (runparams.linelen > 0)
509                                 os << '\n';
510                 }
511                 odocstringstream oss;
512                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
513                 docstring const str = oss.str();
514                 os << str;
515                 // FIXME: len is not computed fully correctly; in principle,
516                 // we have to count the characters after the last '\n'
517                 len = str.size();
518         }
519
520         return len;
521 }
522
523
524 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
525 {
526         ParagraphList::const_iterator const beg = paragraphs().begin();
527
528         if (!undefined())
529                 sgml::openTag(os, getLayout().latexname(),
530                               beg->getID(buffer(), runparams) + getLayout().latexparam());
531
532         docbookParagraphs(text_, buffer(), os, runparams);
533
534         if (!undefined())
535                 sgml::closeTag(os, getLayout().latexname());
536
537         return 0;
538 }
539
540
541 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
542 {
543         return insetAsXHTML(xs, runparams, WriteEverything);
544 }
545
546
547 // FIXME XHTML
548 // There are cases where we may need to close open fonts and such
549 // and then re-open them when we are done. This would be the case, e.g.,
550 // if we were otherwise about to write:
551 //              <em>word <div class='foot'>footnote text.</div> emph</em>
552 // The problem isn't so much that the footnote text will get emphasized:
553 // we can handle that with CSS. The problem is that this is invalid XHTML.
554 // One solution would be to make the footnote <span>, but the problem is
555 // completely general, and so we'd have to make absolutely everything into
556 // span. What I think will work is to check if we're about to write "div" and,
557 // if so, try to close fonts, etc. 
558 // There are probably limits to how well we can do here, though, and we will
559 // have to rely upon users not putting footnotes inside noun-type insets.
560 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & rp,
561                                   XHTMLOptions opts) const
562 {
563         // we will always want to output all our paragraphs when we are
564         // called this way.
565         OutputParams runparams = rp;
566         runparams.par_begin = 0;
567         runparams.par_end = text().paragraphs().size();
568         
569         if (undefined()) {
570                 xhtmlParagraphs(text_, buffer(), xs, runparams);
571                 return docstring();
572         }
573
574         InsetLayout const & il = getLayout();
575         if (opts & WriteOuterTag)
576                 xs << html::StartTag(il.htmltag(), il.htmlattr());
577         if ((opts & WriteLabel) && !il.counter().empty()) {
578                 BufferParams const & bp = buffer().masterBuffer()->params();
579                 Counters & cntrs = bp.documentClass().counters();
580                 cntrs.step(il.counter(), OutputUpdate);
581                 // FIXME: translate to paragraph language
582                 if (!il.htmllabel().empty()) {
583                         docstring const lbl = 
584                                 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
585                         // FIXME is this check necessary?
586                         if (!lbl.empty()) {
587                                 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
588                                 xs << lbl;
589                                 xs << html::EndTag(il.htmllabeltag());
590                         }
591                 }
592         }
593
594         if (opts & WriteInnerTag)
595                 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
596         OutputParams ours = runparams;
597         if (!il.isMultiPar() || opts == JustText)
598                 ours.html_make_pars = false;
599         xhtmlParagraphs(text_, buffer(), xs, ours);
600         if (opts & WriteInnerTag)
601                 xs << html::EndTag(il.htmlinnertag());
602         if (opts & WriteOuterTag)
603                 xs << html::EndTag(il.htmltag());
604         return docstring();
605 }
606
607 void InsetText::getOptArg(otexstream & os,
608                         OutputParams const & runparams) const
609 {
610         latexArgInsets(paragraphs()[0], os, runparams, getLayout().latexargs());
611 }
612
613
614 void InsetText::cursorPos(BufferView const & bv,
615                 CursorSlice const & sl, bool boundary, int & x, int & y) const
616 {
617         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
618         y = bv.textMetrics(&text_).cursorY(sl, boundary);
619 }
620
621
622 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
623 {
624         clear();
625         Paragraph & first = paragraphs().front();
626         for (unsigned int i = 0; i < data.length(); ++i)
627                 first.insertChar(i, data[i], font, trackChanges);
628 }
629
630
631 void InsetText::setAutoBreakRows(bool flag)
632 {
633         if (flag == text_.autoBreakRows_)
634                 return;
635
636         text_.autoBreakRows_ = flag;
637         if (flag)
638                 return;
639
640         // remove previously existing newlines
641         ParagraphList::iterator it = paragraphs().begin();
642         ParagraphList::iterator end = paragraphs().end();
643         for (; it != end; ++it)
644                 for (int i = 0; i < it->size(); ++i)
645                         if (it->isNewline(i))
646                                 // do not track the change, because the user
647                                 // is not allowed to revert/reject it
648                                 it->eraseChar(i, false);
649 }
650
651
652 void InsetText::setDrawFrame(bool flag)
653 {
654         drawFrame_ = flag;
655 }
656
657
658 ColorCode InsetText::frameColor() const
659 {
660         return frame_color_;
661 }
662
663
664 void InsetText::setFrameColor(ColorCode col)
665 {
666         frame_color_ = col;
667 }
668
669
670 void InsetText::appendParagraphs(ParagraphList & plist)
671 {
672         // There is little we can do here to keep track of changes.
673         // As of 2006/10/20, appendParagraphs is used exclusively by
674         // LyXTabular::setMultiColumn. In this context, the paragraph break
675         // is lost irreversibly and the appended text doesn't really change
676
677         ParagraphList & pl = paragraphs();
678
679         ParagraphList::iterator pit = plist.begin();
680         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
681         ++pit;
682         mergeParagraph(buffer().params(), pl,
683                        distance(pl.begin(), ins) - 1);
684
685         for_each(pit, plist.end(),
686                  bind(&ParagraphList::push_back, ref(pl), _1));
687 }
688
689
690 void InsetText::addPreview(DocIterator const & text_inset_pos,
691         PreviewLoader & loader) const
692 {
693         ParagraphList::const_iterator pit = paragraphs().begin();
694         ParagraphList::const_iterator pend = paragraphs().end();
695         int pidx = 0;
696
697         DocIterator inset_pos = text_inset_pos;
698         inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
699
700         for (; pit != pend; ++pit, ++pidx) {
701                 InsetList::const_iterator it  = pit->insetList().begin();
702                 InsetList::const_iterator end = pit->insetList().end();
703                 inset_pos.pit() = pidx;
704                 for (; it != end; ++it) {
705                         inset_pos.pos() = it->pos;
706                         it->inset->addPreview(inset_pos, loader);
707                 }
708         }
709 }
710
711
712 ParagraphList const & InsetText::paragraphs() const
713 {
714         return text_.paragraphs();
715 }
716
717
718 ParagraphList & InsetText::paragraphs()
719 {
720         return text_.paragraphs();
721 }
722
723
724 bool InsetText::insetAllowed(InsetCode code) const
725 {
726         switch (code) {
727         // Arguments are also allowed in PassThru insets
728         case ARG_CODE:
729                 return true;
730         default:
731                 return !getLayout().isPassThru();
732         }
733 }
734
735
736 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
737 {
738         ParIterator it2 = it;
739         it2.forwardPos();
740         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
741         if (producesOutput()) {
742                 InsetLayout const & il = getLayout();
743                 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
744                 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
745                 if (save_layouts) {
746                         // LYXERR0("Entering " << name());
747                         cnt.clearLastLayout();
748                         // FIXME cnt.saveLastCounter()?
749                 }
750                 buffer().updateBuffer(it2, utype);
751                 if (save_layouts) {
752                         // LYXERR0("Exiting " << name());
753                         cnt.restoreLastLayout();
754                         // FIXME cnt.restoreLastCounter()?
755                 }
756         } else {
757                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
758                 // Note that we do not need to call:
759                 //      tclass.counters().clearLastLayout()
760                 // since we are saving and restoring the existing counters, etc.
761                 Counters const savecnt = tclass.counters();
762                 tclass.counters().reset();
763                 buffer().updateBuffer(it2, utype);
764                 tclass.counters() = savecnt;
765         }
766 }
767
768
769 void InsetText::toString(odocstream & os) const
770 {
771         os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
772 }
773
774
775 void InsetText::forToc(docstring & os, size_t maxlen) const
776 {
777         if (!getLayout().isInToc())
778                 return;
779         text().forToc(os, maxlen, false);
780 }
781
782
783 void InsetText::addToToc(DocIterator const & cdit) const
784 {
785         DocIterator dit = cdit;
786         dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
787         Toc & toc = buffer().tocBackend().toc("tableofcontents");
788
789         BufferParams const & bufparams = buffer_->params();
790         int const min_toclevel = bufparams.documentClass().min_toclevel();
791
792         // For each paragraph, traverse its insets and let them add
793         // their toc items
794         ParagraphList const & pars = paragraphs();
795         pit_type pend = paragraphs().size();
796         for (pit_type pit = 0; pit != pend; ++pit) {
797                 Paragraph const & par = pars[pit];
798                 dit.pit() = pit;
799                 // if we find an optarg, we'll save it for use later.
800                 InsetText const * arginset = 0;
801                 InsetList::const_iterator it  = par.insetList().begin();
802                 InsetList::const_iterator end = par.insetList().end();
803                 for (; it != end; ++it) {
804                         Inset & inset = *it->inset;
805                         dit.pos() = it->pos;
806                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
807                         inset.addToToc(dit);
808                         if (inset.lyxCode() == ARG_CODE)
809                                 arginset = inset.asInsetText();
810                 }
811                 // now the toc entry for the paragraph
812                 int const toclevel = par.layout().toclevel;
813                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
814                         // insert this into the table of contents
815                         docstring tocstring;
816                         if (arginset) {
817                                 tocstring = par.labelString();
818                                 if (!tocstring.empty())
819                                         tocstring += ' ';
820                                 arginset->text().forToc(tocstring, TOC_ENTRY_LENGTH);
821                         } else
822                                 par.forToc(tocstring, TOC_ENTRY_LENGTH);
823                         dit.pos() = 0;
824                         toc.push_back(TocItem(dit, toclevel - min_toclevel,
825                                 tocstring, tocstring));
826                 }
827                 
828                 // And now the list of changes.
829                 par.addChangesToToc(dit, buffer());
830         }
831 }
832
833
834 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
835 {
836         if (buffer().isClean())
837                 return Inset::notifyCursorLeaves(old, cur);
838         
839         // find text inset in old cursor
840         Cursor insetCur = old;
841         int scriptSlice = insetCur.find(this);
842         LASSERT(scriptSlice != -1, /**/);
843         insetCur.cutOff(scriptSlice);
844         LASSERT(&insetCur.inset() == this, /**/);
845         
846         // update the old paragraph's words
847         insetCur.paragraph().updateWords();
848         
849         return Inset::notifyCursorLeaves(old, cur);
850 }
851
852
853 bool InsetText::completionSupported(Cursor const & cur) const
854 {
855         //LASSERT(&cur.bv().cursor().inset() != this, return false);
856         return text_.completionSupported(cur);
857 }
858
859
860 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
861 {
862         return completionSupported(cur);
863 }
864
865
866 bool InsetText::automaticInlineCompletion() const
867 {
868         return lyxrc.completion_inline_text;
869 }
870
871
872 bool InsetText::automaticPopupCompletion() const
873 {
874         return lyxrc.completion_popup_text;
875 }
876
877
878 bool InsetText::showCompletionCursor() const
879 {
880         return lyxrc.completion_cursor_text;
881 }
882
883
884 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
885 {
886         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
887 }
888
889
890 docstring InsetText::completionPrefix(Cursor const & cur) const
891 {
892         if (!completionSupported(cur))
893                 return docstring();
894         return text_.completionPrefix(cur);
895 }
896
897
898 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
899         bool finished)
900 {
901         if (!completionSupported(cur))
902                 return false;
903
904         return text_.insertCompletion(cur, s, finished);
905 }
906
907
908 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
909         Dimension & dim) const
910 {
911         TextMetrics const & tm = cur.bv().textMetrics(&text_);
912         tm.completionPosAndDim(cur, x, y, dim);
913 }
914
915
916 string InsetText::contextMenu(BufferView const &, int, int) const
917 {
918         string context_menu = contextMenuName();
919         if (context_menu != InsetText::contextMenuName())
920                 context_menu += ";" + InsetText::contextMenuName(); 
921         return context_menu;
922 }
923
924
925 string InsetText::contextMenuName() const
926 {
927         return "context-edit";
928 }
929
930
931 docstring InsetText::toolTipText(docstring prefix,
932                 size_t numlines, size_t len) const
933 {
934         size_t const max_length = numlines * len;
935         OutputParams rp(&buffer().params().encoding());
936         odocstringstream oss;
937         oss << prefix;
938
939         ParagraphList::const_iterator beg = paragraphs().begin();
940         ParagraphList::const_iterator end = paragraphs().end();
941         ParagraphList::const_iterator it = beg;
942         bool ref_printed = false;
943         docstring str;
944
945         for (; it != end; ++it) {
946                 if (it != beg)
947                         oss << '\n';
948                 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed);
949                 str = oss.str();
950                 if (str.length() > max_length)
951                         break;
952         }
953         return support::wrapParas(str, 4, len, numlines);
954 }
955
956
957 InsetCaption const * InsetText::getCaptionInset() const
958 {
959         ParagraphList::const_iterator pit = paragraphs().begin();
960         for (; pit != paragraphs().end(); ++pit) {
961                 InsetList::const_iterator it = pit->insetList().begin();
962                 for (; it != pit->insetList().end(); ++it) {
963                         Inset & inset = *it->inset;
964                         if (inset.lyxCode() == CAPTION_CODE) {
965                                 InsetCaption const * ins =
966                                         static_cast<InsetCaption const *>(it->inset);
967                                 return ins;
968                         }
969                 }
970         }
971         return 0;
972 }
973
974
975 docstring InsetText::getCaptionText(OutputParams const & runparams) const
976 {
977         InsetCaption const * ins = getCaptionInset();
978         if (ins == 0)
979                 return docstring();
980
981         odocstringstream ods;
982         ins->getCaptionAsPlaintext(ods, runparams);
983         return ods.str();
984 }
985
986
987 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
988 {
989         InsetCaption const * ins = getCaptionInset();
990         if (ins == 0)
991                 return docstring();
992
993         odocstringstream ods;
994         XHTMLStream xs(ods);
995         docstring def = ins->getCaptionAsHTML(xs, runparams);
996         if (!def.empty())
997                 // should already have been escaped
998                 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
999         return ods.str();
1000 }
1001
1002
1003 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
1004 {
1005         return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);
1006 }
1007
1008 } // namespace lyx