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 <boost/bind.hpp>
62 #include "support/lassert.h"
65 using namespace lyx::support;
72 using graphics::PreviewLoader;
75 /////////////////////////////////////////////////////////////////////
77 InsetText::InsetText(Buffer * buf, UsePlain type)
78 : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
79 text_(this, type == DefaultLayout)
84 InsetText::InsetText(InsetText const & in)
85 : Inset(in), text_(this, in.text_)
87 drawFrame_ = in.drawFrame_;
88 frame_color_ = in.frame_color_;
92 void InsetText::setBuffer(Buffer & buf)
94 ParagraphList::iterator end = paragraphs().end();
95 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
97 Inset::setBuffer(buf);
101 void InsetText::clear()
103 ParagraphList & pars = paragraphs();
104 LASSERT(!pars.empty(), /**/);
106 // This is a gross hack...
107 Layout const & old_layout = pars.begin()->layout();
110 pars.push_back(Paragraph());
111 pars.begin()->setInsetOwner(this);
112 pars.begin()->setLayout(old_layout);
116 Dimension const InsetText::dimension(BufferView const & bv) const
118 TextMetrics const & tm = bv.textMetrics(&text_);
119 Dimension dim = tm.dimension();
120 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
121 dim.des += TEXT_TO_INSET_OFFSET;
122 dim.asc += TEXT_TO_INSET_OFFSET;
127 void InsetText::write(ostream & os) const
134 void InsetText::read(Lexer & lex)
138 // delete the initial paragraph
139 Paragraph oldpar = *paragraphs().begin();
140 paragraphs().clear();
142 lex.setContext("InsetText::read");
143 bool res = text_.read(lex, errorList, this);
146 lex.printError("Missing \\end_inset at this point. ");
149 // ensure we have at least one paragraph.
150 if (paragraphs().empty())
151 paragraphs().push_back(oldpar);
152 // Force default font, if so requested
153 // This avoids paragraphs in buffer language that would have a
154 // foreign language after a document language change, and it ensures
155 // that all new text in ERT and similar gets the "latex" language,
156 // since new text inherits the language from the last position of the
157 // existing text. As a side effect this makes us also robust against
158 // bugs in LyX that might lead to font changes in ERT in .lyx files.
163 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
165 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
167 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
169 // Hand font through to contained lyxtext:
170 tm.font_.fontInfo() = mi.base.font;
171 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
173 // This can happen when a layout has a left and right margin,
174 // and the view is made very narrow. We can't do better than
175 // to draw it partly out of view (bug 5890).
176 if (mi.base.textwidth < 1)
177 mi.base.textwidth = 1;
180 tm.metrics(mi, dim, mi.base.textwidth);
183 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
184 dim.asc += TEXT_TO_INSET_OFFSET;
185 dim.des += TEXT_TO_INSET_OFFSET;
186 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
190 void InsetText::draw(PainterInfo & pi, int x, int y) const
192 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
194 if (drawFrame_ || pi.full_repaint) {
195 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
196 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
197 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
198 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
200 pi.pain.fillRectangle(xframe, yframe, w, h,
201 pi.backgroundColor(this));
204 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
206 ColorCode const old_color = pi.background_color;
207 pi.background_color = pi.backgroundColor(this, false);
209 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
211 pi.background_color = old_color;
215 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
217 pit_type const pit = front ? 0 : paragraphs().size() - 1;
218 pos_type pos = front ? 0 : paragraphs().back().size();
220 // if visual information is not to be ignored, move to extreme right/left
221 if (entry_from != ENTRY_DIRECTION_IGNORE) {
222 Cursor temp_cur = cur;
223 temp_cur.pit() = pit;
224 temp_cur.pos() = pos;
225 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
226 pos = temp_cur.pos();
229 text_.setCursor(cur.top(), pit, pos);
230 cur.clearSelection();
235 Inset * InsetText::editXY(Cursor & cur, int x, int y)
237 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
241 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
243 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
244 << " [ cmd.action = " << cmd.action << ']');
246 if (getLayout().isPassThru()) {
247 // Force any new text to latex_language FIXME: This
248 // should only be necessary in constructor, but new
249 // paragraphs that are created by pressing enter at
250 // the start of an existing paragraph get the buffer
251 // language and not latex_language, so we take this
252 // brute force approach.
253 cur.current_font.setLanguage(latex_language);
254 cur.real_current_font.setLanguage(latex_language);
257 switch (cmd.action) {
259 case LFUN_CLIPBOARD_PASTE:
260 case LFUN_SELECTION_PASTE:
261 case LFUN_PRIMARY_SELECTION_PASTE:
262 text_.dispatch(cur, cmd);
263 // If we we can only store plain text, we must reset all
265 // FIXME: Change only the pasted paragraphs
269 case LFUN_INSET_DISSOLVE: {
270 bool const main_inset = &buffer().inset() == this;
271 bool const target_inset = cmd.argument().empty()
272 || cmd.getArg(0) == insetName(lyxCode());
273 bool const one_cell = nargs() == 1;
275 if (!main_inset && target_inset && one_cell) {
276 // Text::dissolveInset assumes that the cursor
277 // is inside the Inset.
278 if (&cur.inset() != this)
279 cur.pushBackward(*this);
280 cur.beginUndoGroup();
281 text_.dispatch(cur, cmd);
289 text_.dispatch(cur, cmd);
292 if (!cur.result().dispatched())
293 Inset::doDispatch(cur, cmd);
297 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
298 FuncStatus & status) const
300 switch (cmd.action) {
302 status.setEnabled(!forcePlainLayout());
305 case LFUN_LAYOUT_PARAGRAPH:
306 case LFUN_PARAGRAPH_PARAMS:
307 case LFUN_PARAGRAPH_PARAMS_APPLY:
308 case LFUN_PARAGRAPH_UPDATE:
309 status.setEnabled(allowParagraphCustomization());
312 case LFUN_INSET_DISSOLVE: {
313 bool const main_inset = &buffer().inset() == this;
314 bool const target_inset = cmd.argument().empty()
315 || cmd.getArg(0) == insetName(lyxCode());
316 bool const one_cell = nargs() == 1;
319 status.setEnabled(!main_inset && one_cell);
324 // Dispatch only to text_ if the cursor is inside
325 // the text_. It is not for context menus (bug 5797).
327 if (cur.text() == &text_)
328 ret = text_.getStatus(cur, cmd, status);
331 ret = Inset::getStatus(cur, cmd, status);
337 void InsetText::fixParagraphsFont()
339 if (!getLayout().isPassThru())
342 Font font(inherit_font, buffer().params().language);
343 font.setLanguage(latex_language);
344 ParagraphList::iterator par = paragraphs().begin();
345 ParagraphList::iterator const end = paragraphs().end();
347 par->resetFonts(font);
348 par->params().clear();
354 void InsetText::setChange(Change const & change)
356 ParagraphList::iterator pit = paragraphs().begin();
357 ParagraphList::iterator end = paragraphs().end();
358 for (; pit != end; ++pit) {
359 pit->setChange(change);
364 void InsetText::acceptChanges()
366 text_.acceptChanges();
370 void InsetText::rejectChanges()
372 text_.rejectChanges();
376 void InsetText::validate(LaTeXFeatures & features) const
378 features.useInsetLayout(getLayout());
379 for_each(paragraphs().begin(), paragraphs().end(),
380 bind(&Paragraph::validate, _1, ref(features)));
384 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
386 // This implements the standard way of handling the LaTeX
387 // output of a text inset, either a command or an
388 // environment. Standard collapsable insets should not
389 // redefine this, non-standard ones may call this.
390 InsetLayout const & il = getLayout();
392 if (!il.latexname().empty()) {
393 if (il.latextype() == InsetLayout::COMMAND) {
395 if (runparams.moving_arg)
397 os << '\\' << from_utf8(il.latexname());
398 if (!il.latexparam().empty())
399 os << from_utf8(il.latexparam());
401 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
402 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
403 if (!il.latexparam().empty())
404 os << from_utf8(il.latexparam());
408 OutputParams rp = runparams;
411 if (il.isNeedProtect())
412 rp.moving_arg = true;
414 // Output the contents of the inset
416 latexParagraphs(buffer(), text_, os, texrow, rp);
417 rows += texrow.rows();
419 if (!il.latexname().empty()) {
420 if (il.latextype() == InsetLayout::COMMAND) {
422 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
423 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
431 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
433 ParagraphList::const_iterator beg = paragraphs().begin();
434 ParagraphList::const_iterator end = paragraphs().end();
435 ParagraphList::const_iterator it = beg;
436 bool ref_printed = false;
438 for (; it != end; ++it) {
441 if (runparams.linelen > 0)
444 odocstringstream oss;
445 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
446 docstring const str = oss.str();
448 // FIXME: len is not computed fully correctly; in principle,
449 // we have to count the characters after the last '\n'
457 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
459 ParagraphList::const_iterator const beg = paragraphs().begin();
462 sgml::openTag(os, getLayout().latexname(),
463 beg->getID(buffer(), runparams) + getLayout().latexparam());
465 docbookParagraphs(text_, buffer(), os, runparams);
468 sgml::closeTag(os, getLayout().latexname());
474 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
476 return insetAsXHTML(xs, runparams, WriteEverything);
481 // There are cases where we may need to close open fonts and such
482 // and then re-open them when we are done. This would be the case, e.g.,
483 // if we were otherwise about to write:
484 // <em>word <div class='foot'>footnote text.</div> emph</em>
485 // The problem isn't so much that the footnote text will get emphasized:
486 // we can handle that with CSS. The problem is that this is invalid XHTML.
487 // One solution would be to make the footnote <span>, but the problem is
488 // completely general, and so we'd have to make absolutely everything into
489 // span. What I think will work is to check if we're about to write "div" and,
490 // if so, try to close fonts, etc.
491 // There are probably limits to how well we can do here, though, and we will
492 // have to rely upon users not putting footnotes inside noun-type insets.
493 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & runparams,
494 XHTMLOptions opts) const
497 xhtmlParagraphs(text_, buffer(), xs, runparams);
501 InsetLayout const & il = getLayout();
502 if (opts & WriteOuterTag)
503 xs << html::StartTag(il.htmltag(), il.htmlattr());
504 if ((opts & WriteLabel) && !il.counter().empty()) {
505 BufferParams const & bp = buffer().masterBuffer()->params();
506 Counters & cntrs = bp.documentClass().counters();
507 cntrs.step(il.counter());
508 // FIXME: translate to paragraph language
509 if (!il.htmllabel().empty()) {
510 docstring const lbl =
511 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
512 // FIXME is this check necessary?
514 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
516 xs << html::EndTag(il.htmllabeltag());
521 if (opts & WriteInnerTag)
522 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
523 OutputParams ours = runparams;
524 if (!il.isMultiPar() || opts == JustText)
525 ours.html_make_pars = false;
526 xhtmlParagraphs(text_, buffer(), xs, ours);
527 if (opts & WriteInnerTag)
528 xs << html::EndTag(il.htmlinnertag());
529 if (opts & WriteOuterTag)
530 xs << html::EndTag(il.htmltag());
535 void InsetText::cursorPos(BufferView const & bv,
536 CursorSlice const & sl, bool boundary, int & x, int & y) const
538 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
539 y = bv.textMetrics(&text_).cursorY(sl, boundary);
543 bool InsetText::showInsetDialog(BufferView *) const
549 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
552 Paragraph & first = paragraphs().front();
553 for (unsigned int i = 0; i < data.length(); ++i)
554 first.insertChar(i, data[i], font, trackChanges);
558 void InsetText::setAutoBreakRows(bool flag)
560 if (flag == text_.autoBreakRows_)
563 text_.autoBreakRows_ = flag;
567 // remove previously existing newlines
568 ParagraphList::iterator it = paragraphs().begin();
569 ParagraphList::iterator end = paragraphs().end();
570 for (; it != end; ++it)
571 for (int i = 0; i < it->size(); ++i)
572 if (it->isNewline(i))
573 // do not track the change, because the user
574 // is not allowed to revert/reject it
575 it->eraseChar(i, false);
579 void InsetText::setDrawFrame(bool flag)
585 ColorCode InsetText::frameColor() const
591 void InsetText::setFrameColor(ColorCode col)
597 void InsetText::appendParagraphs(ParagraphList & plist)
599 // There is little we can do here to keep track of changes.
600 // As of 2006/10/20, appendParagraphs is used exclusively by
601 // LyXTabular::setMultiColumn. In this context, the paragraph break
602 // is lost irreversibly and the appended text doesn't really change
604 ParagraphList & pl = paragraphs();
606 ParagraphList::iterator pit = plist.begin();
607 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
609 mergeParagraph(buffer().params(), pl,
610 distance(pl.begin(), ins) - 1);
612 for_each(pit, plist.end(),
613 bind(&ParagraphList::push_back, ref(pl), _1));
617 void InsetText::addPreview(DocIterator const & text_inset_pos,
618 PreviewLoader & loader) const
620 ParagraphList::const_iterator pit = paragraphs().begin();
621 ParagraphList::const_iterator pend = paragraphs().end();
624 DocIterator inset_pos = text_inset_pos;
625 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
627 for (; pit != pend; ++pit, ++pidx) {
628 InsetList::const_iterator it = pit->insetList().begin();
629 InsetList::const_iterator end = pit->insetList().end();
630 inset_pos.pit() = pidx;
631 for (; it != end; ++it) {
632 inset_pos.pos() = it->pos;
633 it->inset->addPreview(inset_pos, loader);
639 ParagraphList const & InsetText::paragraphs() const
641 return text_.paragraphs();
645 ParagraphList & InsetText::paragraphs()
647 return text_.paragraphs();
651 void InsetText::updateLabels(ParIterator const & it, bool out)
653 ParIterator it2 = it;
655 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
656 if (producesOutput())
657 buffer().updateLabels(it2, out);
659 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
660 Counters const savecnt = tclass.counters();
661 buffer().updateLabels(it2, out);
662 tclass.counters() = savecnt;
667 void InsetText::tocString(odocstream & os) const
669 if (!getLayout().isInToc())
671 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
676 void InsetText::addToToc(DocIterator const & cdit)
678 DocIterator dit = cdit;
679 dit.push_back(CursorSlice(*this));
680 Toc & toc = buffer().tocBackend().toc("tableofcontents");
682 BufferParams const & bufparams = buffer_->params();
683 const int min_toclevel = bufparams.documentClass().min_toclevel();
685 // For each paragraph, traverse its insets and let them add
687 ParagraphList & pars = paragraphs();
688 pit_type pend = paragraphs().size();
689 for (pit_type pit = 0; pit != pend; ++pit) {
690 Paragraph const & par = pars[pit];
692 // the string that goes to the toc (could be the optarg)
694 InsetList::const_iterator it = par.insetList().begin();
695 InsetList::const_iterator end = par.insetList().end();
696 for (; it != end; ++it) {
697 Inset & inset = *it->inset;
699 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
701 switch (inset.lyxCode()) {
703 if (!tocstring.empty())
706 Paragraph const & insetpar =
707 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
708 if (!par.labelString().empty())
709 tocstring = par.labelString() + ' ';
710 tocstring += insetpar.asString(AS_STR_INSETS);
717 // now the toc entry for the paragraph
718 int const toclevel = par.layout().toclevel;
719 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
721 // insert this into the table of contents
722 if (tocstring.empty())
723 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
724 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
727 // And now the list of changes.
728 par.addChangesToToc(dit, buffer());
733 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
735 if (buffer().isClean())
736 return Inset::notifyCursorLeaves(old, cur);
738 // find text inset in old cursor
739 Cursor insetCur = old;
740 int scriptSlice = insetCur.find(this);
741 LASSERT(scriptSlice != -1, /**/);
742 insetCur.cutOff(scriptSlice);
743 LASSERT(&insetCur.inset() == this, /**/);
745 // update the old paragraph's words
746 insetCur.paragraph().updateWords();
748 return Inset::notifyCursorLeaves(old, cur);
752 bool InsetText::completionSupported(Cursor const & cur) const
754 //LASSERT(&cur.bv().cursor().inset() != this, return false);
755 return text_.completionSupported(cur);
759 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
761 return completionSupported(cur);
765 bool InsetText::automaticInlineCompletion() const
767 return lyxrc.completion_inline_text;
771 bool InsetText::automaticPopupCompletion() const
773 return lyxrc.completion_popup_text;
777 bool InsetText::showCompletionCursor() const
779 return lyxrc.completion_cursor_text;
783 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
785 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
789 docstring InsetText::completionPrefix(Cursor const & cur) const
791 if (!completionSupported(cur))
793 return text_.completionPrefix(cur);
797 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
800 if (!completionSupported(cur))
803 return text_.insertCompletion(cur, s, finished);
807 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
808 Dimension & dim) const
810 TextMetrics const & tm = cur.bv().textMetrics(&text_);
811 tm.completionPosAndDim(cur, x, y, dim);
815 docstring InsetText::contextMenu(BufferView const &, int, int) const
817 return from_ascii("context-edit");
821 InsetCaption const * InsetText::getCaptionInset() const
823 ParagraphList::const_iterator pit = paragraphs().begin();
824 for (; pit != paragraphs().end(); ++pit) {
825 InsetList::const_iterator it = pit->insetList().begin();
826 for (; it != pit->insetList().end(); ++it) {
827 Inset & inset = *it->inset;
828 if (inset.lyxCode() == CAPTION_CODE) {
829 InsetCaption const * ins =
830 static_cast<InsetCaption const *>(it->inset);
839 docstring InsetText::getCaptionText(OutputParams const & runparams) const
841 InsetCaption const * ins = getCaptionInset();
845 odocstringstream ods;
846 ins->getCaptionAsPlaintext(ods, runparams);
851 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
853 InsetCaption const * ins = getCaptionInset();
857 odocstringstream ods;
859 docstring def = ins->getCaptionAsHTML(xs, runparams);
861 // should already have been escaped
862 xs << XHTMLStream::NextRaw() << def << '\n';
867 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
869 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);