3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetText.h"
15 #include "insets/InsetOptArg.h"
17 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetCaption.h"
30 #include "InsetList.h"
33 #include "LaTeXFeatures.h"
37 #include "MetricsInfo.h"
38 #include "output_docbook.h"
39 #include "output_latex.h"
40 #include "output_xhtml.h"
41 #include "OutputParams.h"
42 #include "output_plaintext.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
49 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
54 #include "frontends/alert.h"
55 #include "frontends/Painter.h"
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
61 #include "support/bind.h"
62 #include "support/lassert.h"
65 using namespace lyx::support;
70 using graphics::PreviewLoader;
73 /////////////////////////////////////////////////////////////////////
75 InsetText::InsetText(Buffer * buf, UsePlain type)
76 : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
77 text_(this, type == DefaultLayout)
82 InsetText::InsetText(InsetText const & in)
83 : Inset(in), text_(this, in.text_)
85 drawFrame_ = in.drawFrame_;
86 frame_color_ = in.frame_color_;
90 void InsetText::setBuffer(Buffer & buf)
92 ParagraphList::iterator end = paragraphs().end();
93 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
95 Inset::setBuffer(buf);
99 void InsetText::clear()
101 ParagraphList & pars = paragraphs();
102 LASSERT(!pars.empty(), /**/);
104 // This is a gross hack...
105 Layout const & old_layout = pars.begin()->layout();
108 pars.push_back(Paragraph());
109 pars.begin()->setInsetOwner(this);
110 pars.begin()->setLayout(old_layout);
114 Dimension const InsetText::dimension(BufferView const & bv) const
116 TextMetrics const & tm = bv.textMetrics(&text_);
117 Dimension dim = tm.dimension();
118 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
119 dim.des += TEXT_TO_INSET_OFFSET;
120 dim.asc += TEXT_TO_INSET_OFFSET;
125 void InsetText::write(ostream & os) const
132 void InsetText::read(Lexer & lex)
136 // delete the initial paragraph
137 Paragraph oldpar = *paragraphs().begin();
138 paragraphs().clear();
140 lex.setContext("InsetText::read");
141 bool res = text_.read(lex, errorList, this);
144 lex.printError("Missing \\end_inset at this point. ");
147 // ensure we have at least one paragraph.
148 if (paragraphs().empty())
149 paragraphs().push_back(oldpar);
150 // Force default font, if so requested
151 // This avoids paragraphs in buffer language that would have a
152 // foreign language after a document language change, and it ensures
153 // that all new text in ERT and similar gets the "latex" language,
154 // since new text inherits the language from the last position of the
155 // existing text. As a side effect this makes us also robust against
156 // bugs in LyX that might lead to font changes in ERT in .lyx files.
161 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
163 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
165 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
167 // Hand font through to contained lyxtext:
168 tm.font_.fontInfo() = mi.base.font;
169 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
171 // This can happen when a layout has a left and right margin,
172 // and the view is made very narrow. We can't do better than
173 // to draw it partly out of view (bug 5890).
174 if (mi.base.textwidth < 1)
175 mi.base.textwidth = 1;
178 tm.metrics(mi, dim, mi.base.textwidth);
181 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
182 dim.asc += TEXT_TO_INSET_OFFSET;
183 dim.des += TEXT_TO_INSET_OFFSET;
184 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
188 void InsetText::draw(PainterInfo & pi, int x, int y) const
190 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
192 if (drawFrame_ || pi.full_repaint) {
193 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
194 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
195 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
196 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
198 pi.pain.fillRectangle(xframe, yframe, w, h,
199 pi.backgroundColor(this));
202 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
204 ColorCode const old_color = pi.background_color;
205 pi.background_color = pi.backgroundColor(this, false);
207 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
209 pi.background_color = old_color;
213 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
215 pit_type const pit = front ? 0 : paragraphs().size() - 1;
216 pos_type pos = front ? 0 : paragraphs().back().size();
218 // if visual information is not to be ignored, move to extreme right/left
219 if (entry_from != ENTRY_DIRECTION_IGNORE) {
220 Cursor temp_cur = cur;
221 temp_cur.pit() = pit;
222 temp_cur.pos() = pos;
223 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
224 pos = temp_cur.pos();
227 text_.setCursor(cur.top(), pit, pos);
228 cur.clearSelection();
233 Inset * InsetText::editXY(Cursor & cur, int x, int y)
235 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
239 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
241 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
242 << " [ cmd.action() = " << cmd.action() << ']');
244 if (getLayout().isPassThru()) {
245 // Force any new text to latex_language FIXME: This
246 // should only be necessary in constructor, but new
247 // paragraphs that are created by pressing enter at
248 // the start of an existing paragraph get the buffer
249 // language and not latex_language, so we take this
250 // brute force approach.
251 cur.current_font.setLanguage(latex_language);
252 cur.real_current_font.setLanguage(latex_language);
255 switch (cmd.action()) {
257 case LFUN_CLIPBOARD_PASTE:
258 case LFUN_SELECTION_PASTE:
259 case LFUN_PRIMARY_SELECTION_PASTE:
260 text_.dispatch(cur, cmd);
261 // If we we can only store plain text, we must reset all
263 // FIXME: Change only the pasted paragraphs
267 case LFUN_INSET_DISSOLVE: {
268 bool const main_inset = &buffer().inset() == this;
269 bool const target_inset = cmd.argument().empty()
270 || cmd.getArg(0) == insetName(lyxCode());
271 bool const one_cell = nargs() == 1;
273 if (!main_inset && target_inset && one_cell) {
274 // Text::dissolveInset assumes that the cursor
275 // is inside the Inset.
276 if (&cur.inset() != this)
277 cur.pushBackward(*this);
278 cur.beginUndoGroup();
279 text_.dispatch(cur, cmd);
287 text_.dispatch(cur, cmd);
290 if (!cur.result().dispatched())
291 Inset::doDispatch(cur, cmd);
295 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
296 FuncStatus & status) const
298 switch (cmd.action()) {
299 case LFUN_INSET_DISSOLVE: {
300 bool const main_inset = &buffer().inset() == this;
301 bool const target_inset = cmd.argument().empty()
302 || cmd.getArg(0) == insetName(lyxCode());
303 bool const one_cell = nargs() == 1;
306 status.setEnabled(!main_inset && one_cell);
311 // Dispatch only to text_ if the cursor is inside
312 // the text_. It is not for context menus (bug 5797).
314 if (cur.text() == &text_)
315 ret = text_.getStatus(cur, cmd, status);
318 ret = Inset::getStatus(cur, cmd, status);
324 void InsetText::fixParagraphsFont()
326 if (!getLayout().isPassThru())
329 Font font(inherit_font, buffer().params().language);
330 font.setLanguage(latex_language);
331 ParagraphList::iterator par = paragraphs().begin();
332 ParagraphList::iterator const end = paragraphs().end();
334 par->resetFonts(font);
335 par->params().clear();
341 void InsetText::setChange(Change const & change)
343 ParagraphList::iterator pit = paragraphs().begin();
344 ParagraphList::iterator end = paragraphs().end();
345 for (; pit != end; ++pit) {
346 pit->setChange(change);
351 void InsetText::acceptChanges()
353 text_.acceptChanges();
357 void InsetText::rejectChanges()
359 text_.rejectChanges();
363 void InsetText::validate(LaTeXFeatures & features) const
365 features.useInsetLayout(getLayout());
366 for_each(paragraphs().begin(), paragraphs().end(),
367 bind(&Paragraph::validate, _1, ref(features)));
371 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
373 // This implements the standard way of handling the LaTeX
374 // output of a text inset, either a command or an
375 // environment. Standard collapsable insets should not
376 // redefine this, non-standard ones may call this.
377 InsetLayout const & il = getLayout();
379 if (!il.latexname().empty()) {
380 if (il.latextype() == InsetLayout::COMMAND) {
382 if (runparams.moving_arg)
384 os << '\\' << from_utf8(il.latexname());
385 if (!il.latexparam().empty())
386 os << from_utf8(il.latexparam());
388 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
389 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
390 if (!il.latexparam().empty())
391 os << from_utf8(il.latexparam());
395 OutputParams rp = runparams;
398 if (il.isNeedProtect())
399 rp.moving_arg = true;
401 // Output the contents of the inset
403 latexParagraphs(buffer(), text_, os, texrow, rp);
404 rows += texrow.rows();
406 if (!il.latexname().empty()) {
407 if (il.latextype() == InsetLayout::COMMAND) {
409 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
410 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
418 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
420 ParagraphList::const_iterator beg = paragraphs().begin();
421 ParagraphList::const_iterator end = paragraphs().end();
422 ParagraphList::const_iterator it = beg;
423 bool ref_printed = false;
425 for (; it != end; ++it) {
428 if (runparams.linelen > 0)
431 odocstringstream oss;
432 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
433 docstring const str = oss.str();
435 // FIXME: len is not computed fully correctly; in principle,
436 // we have to count the characters after the last '\n'
444 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
446 ParagraphList::const_iterator const beg = paragraphs().begin();
449 sgml::openTag(os, getLayout().latexname(),
450 beg->getID(buffer(), runparams) + getLayout().latexparam());
452 docbookParagraphs(text_, buffer(), os, runparams);
455 sgml::closeTag(os, getLayout().latexname());
461 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
463 return insetAsXHTML(xs, runparams, WriteEverything);
468 // There are cases where we may need to close open fonts and such
469 // and then re-open them when we are done. This would be the case, e.g.,
470 // if we were otherwise about to write:
471 // <em>word <div class='foot'>footnote text.</div> emph</em>
472 // The problem isn't so much that the footnote text will get emphasized:
473 // we can handle that with CSS. The problem is that this is invalid XHTML.
474 // One solution would be to make the footnote <span>, but the problem is
475 // completely general, and so we'd have to make absolutely everything into
476 // span. What I think will work is to check if we're about to write "div" and,
477 // if so, try to close fonts, etc.
478 // There are probably limits to how well we can do here, though, and we will
479 // have to rely upon users not putting footnotes inside noun-type insets.
480 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & runparams,
481 XHTMLOptions opts) const
484 xhtmlParagraphs(text_, buffer(), xs, runparams);
488 InsetLayout const & il = getLayout();
489 if (opts & WriteOuterTag)
490 xs << html::StartTag(il.htmltag(), il.htmlattr());
491 if ((opts & WriteLabel) && !il.counter().empty()) {
492 BufferParams const & bp = buffer().masterBuffer()->params();
493 Counters & cntrs = bp.documentClass().counters();
494 cntrs.step(il.counter(), OutputUpdate);
495 // FIXME: translate to paragraph language
496 if (!il.htmllabel().empty()) {
497 docstring const lbl =
498 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
499 // FIXME is this check necessary?
501 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
503 xs << html::EndTag(il.htmllabeltag());
508 if (opts & WriteInnerTag)
509 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
510 OutputParams ours = runparams;
511 if (!il.isMultiPar() || opts == JustText)
512 ours.html_make_pars = false;
513 xhtmlParagraphs(text_, buffer(), xs, ours);
514 if (opts & WriteInnerTag)
515 xs << html::EndTag(il.htmlinnertag());
516 if (opts & WriteOuterTag)
517 xs << html::EndTag(il.htmltag());
522 void InsetText::cursorPos(BufferView const & bv,
523 CursorSlice const & sl, bool boundary, int & x, int & y) const
525 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
526 y = bv.textMetrics(&text_).cursorY(sl, boundary);
530 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
533 Paragraph & first = paragraphs().front();
534 for (unsigned int i = 0; i < data.length(); ++i)
535 first.insertChar(i, data[i], font, trackChanges);
539 void InsetText::setAutoBreakRows(bool flag)
541 if (flag == text_.autoBreakRows_)
544 text_.autoBreakRows_ = flag;
548 // remove previously existing newlines
549 ParagraphList::iterator it = paragraphs().begin();
550 ParagraphList::iterator end = paragraphs().end();
551 for (; it != end; ++it)
552 for (int i = 0; i < it->size(); ++i)
553 if (it->isNewline(i))
554 // do not track the change, because the user
555 // is not allowed to revert/reject it
556 it->eraseChar(i, false);
560 void InsetText::setDrawFrame(bool flag)
566 ColorCode InsetText::frameColor() const
572 void InsetText::setFrameColor(ColorCode col)
578 void InsetText::appendParagraphs(ParagraphList & plist)
580 // There is little we can do here to keep track of changes.
581 // As of 2006/10/20, appendParagraphs is used exclusively by
582 // LyXTabular::setMultiColumn. In this context, the paragraph break
583 // is lost irreversibly and the appended text doesn't really change
585 ParagraphList & pl = paragraphs();
587 ParagraphList::iterator pit = plist.begin();
588 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
590 mergeParagraph(buffer().params(), pl,
591 distance(pl.begin(), ins) - 1);
593 for_each(pit, plist.end(),
594 bind(&ParagraphList::push_back, ref(pl), _1));
598 void InsetText::addPreview(DocIterator const & text_inset_pos,
599 PreviewLoader & loader) const
601 ParagraphList::const_iterator pit = paragraphs().begin();
602 ParagraphList::const_iterator pend = paragraphs().end();
605 DocIterator inset_pos = text_inset_pos;
606 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
608 for (; pit != pend; ++pit, ++pidx) {
609 InsetList::const_iterator it = pit->insetList().begin();
610 InsetList::const_iterator end = pit->insetList().end();
611 inset_pos.pit() = pidx;
612 for (; it != end; ++it) {
613 inset_pos.pos() = it->pos;
614 it->inset->addPreview(inset_pos, loader);
620 ParagraphList const & InsetText::paragraphs() const
622 return text_.paragraphs();
626 ParagraphList & InsetText::paragraphs()
628 return text_.paragraphs();
632 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
634 ParIterator it2 = it;
636 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
637 if (producesOutput()) {
638 InsetLayout const & il = getLayout();
639 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
640 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
642 // LYXERR0("Entering " << name());
643 cnt.clearLastLayout();
644 // FIXME cnt.saveLastCounter()?
646 buffer().updateBuffer(it2, utype);
648 // LYXERR0("Exiting " << name());
649 cnt.restoreLastLayout();
650 // FIXME cnt.restoreLastCounter()?
653 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
654 // Note that we do not need to call:
655 // tclass.counters().clearLastLayout()
656 // since we are saving and restoring the existing counters, etc.
657 Counters const savecnt = tclass.counters();
658 buffer().updateBuffer(it2, utype);
659 tclass.counters() = savecnt;
664 void InsetText::tocString(odocstream & os) const
666 if (!getLayout().isInToc())
668 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
673 void InsetText::addToToc(DocIterator const & cdit)
675 DocIterator dit = cdit;
676 dit.push_back(CursorSlice(*this));
677 Toc & toc = buffer().tocBackend().toc("tableofcontents");
679 BufferParams const & bufparams = buffer_->params();
680 const int min_toclevel = bufparams.documentClass().min_toclevel();
682 // For each paragraph, traverse its insets and let them add
684 ParagraphList & pars = paragraphs();
685 pit_type pend = paragraphs().size();
686 for (pit_type pit = 0; pit != pend; ++pit) {
687 Paragraph const & par = pars[pit];
689 // the string that goes to the toc (could be the optarg)
691 InsetList::const_iterator it = par.insetList().begin();
692 InsetList::const_iterator end = par.insetList().end();
693 for (; it != end; ++it) {
694 Inset & inset = *it->inset;
696 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
698 switch (inset.lyxCode()) {
700 if (!tocstring.empty())
703 Paragraph const & insetpar =
704 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
705 if (!par.labelString().empty())
706 tocstring = par.labelString() + ' ';
707 tocstring += insetpar.asString(AS_STR_INSETS);
714 // now the toc entry for the paragraph
715 int const toclevel = par.layout().toclevel;
716 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
718 // insert this into the table of contents
719 if (tocstring.empty())
720 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
721 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
724 // And now the list of changes.
725 par.addChangesToToc(dit, buffer());
730 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
732 if (buffer().isClean())
733 return Inset::notifyCursorLeaves(old, cur);
735 // find text inset in old cursor
736 Cursor insetCur = old;
737 int scriptSlice = insetCur.find(this);
738 LASSERT(scriptSlice != -1, /**/);
739 insetCur.cutOff(scriptSlice);
740 LASSERT(&insetCur.inset() == this, /**/);
742 // update the old paragraph's words
743 insetCur.paragraph().updateWords();
745 return Inset::notifyCursorLeaves(old, cur);
749 bool InsetText::completionSupported(Cursor const & cur) const
751 //LASSERT(&cur.bv().cursor().inset() != this, return false);
752 return text_.completionSupported(cur);
756 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
758 return completionSupported(cur);
762 bool InsetText::automaticInlineCompletion() const
764 return lyxrc.completion_inline_text;
768 bool InsetText::automaticPopupCompletion() const
770 return lyxrc.completion_popup_text;
774 bool InsetText::showCompletionCursor() const
776 return lyxrc.completion_cursor_text;
780 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
782 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
786 docstring InsetText::completionPrefix(Cursor const & cur) const
788 if (!completionSupported(cur))
790 return text_.completionPrefix(cur);
794 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
797 if (!completionSupported(cur))
800 return text_.insertCompletion(cur, s, finished);
804 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
805 Dimension & dim) const
807 TextMetrics const & tm = cur.bv().textMetrics(&text_);
808 tm.completionPosAndDim(cur, x, y, dim);
812 docstring InsetText::contextMenu(BufferView const &, int, int) const
814 return from_ascii("context-edit");
818 InsetCaption const * InsetText::getCaptionInset() const
820 ParagraphList::const_iterator pit = paragraphs().begin();
821 for (; pit != paragraphs().end(); ++pit) {
822 InsetList::const_iterator it = pit->insetList().begin();
823 for (; it != pit->insetList().end(); ++it) {
824 Inset & inset = *it->inset;
825 if (inset.lyxCode() == CAPTION_CODE) {
826 InsetCaption const * ins =
827 static_cast<InsetCaption const *>(it->inset);
836 docstring InsetText::getCaptionText(OutputParams const & runparams) const
838 InsetCaption const * ins = getCaptionInset();
842 odocstringstream ods;
843 ins->getCaptionAsPlaintext(ods, runparams);
848 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
850 InsetCaption const * ins = getCaptionInset();
854 odocstringstream ods;
856 docstring def = ins->getCaptionAsHTML(xs, runparams);
858 // should already have been escaped
859 xs << XHTMLStream::NextRaw() << def << '\n';
864 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
866 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);