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