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/InsetArgument.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"
68 using namespace lyx::support;
73 using graphics::PreviewLoader;
76 /////////////////////////////////////////////////////////////////////
78 InsetText::InsetText(Buffer * buf, UsePlain type)
79 : Inset(buf), drawFrame_(false), frame_color_(Color_insetframe),
80 text_(this, type == DefaultLayout)
85 InsetText::InsetText(InsetText const & in)
86 : Inset(in), text_(this, in.text_)
88 drawFrame_ = in.drawFrame_;
89 frame_color_ = in.frame_color_;
93 void InsetText::setBuffer(Buffer & buf)
95 ParagraphList::iterator end = paragraphs().end();
96 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
98 Inset::setBuffer(buf);
102 void InsetText::clear()
104 ParagraphList & pars = paragraphs();
105 LASSERT(!pars.empty(), /**/);
107 // This is a gross hack...
108 Layout const & old_layout = pars.begin()->layout();
111 pars.push_back(Paragraph());
112 pars.begin()->setInsetOwner(this);
113 pars.begin()->setLayout(old_layout);
117 Dimension const InsetText::dimension(BufferView const & bv) const
119 TextMetrics const & tm = bv.textMetrics(&text_);
120 Dimension dim = tm.dimension();
121 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
122 dim.des += TEXT_TO_INSET_OFFSET;
123 dim.asc += TEXT_TO_INSET_OFFSET;
128 void InsetText::write(ostream & os) const
135 void InsetText::read(Lexer & lex)
139 // delete the initial paragraph
140 Paragraph oldpar = *paragraphs().begin();
141 paragraphs().clear();
143 lex.setContext("InsetText::read");
144 bool res = text_.read(lex, errorList, this);
147 lex.printError("Missing \\end_inset at this point. ");
150 // ensure we have at least one paragraph.
151 if (paragraphs().empty())
152 paragraphs().push_back(oldpar);
153 // Force default font, if so requested
154 // This avoids paragraphs in buffer language that would have a
155 // foreign language after a document language change, and it ensures
156 // that all new text in ERT and similar gets the "latex" language,
157 // since new text inherits the language from the last position of the
158 // existing text. As a side effect this makes us also robust against
159 // bugs in LyX that might lead to font changes in ERT in .lyx files.
164 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
166 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
168 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
170 // Hand font through to contained lyxtext:
171 tm.font_.fontInfo() = mi.base.font;
172 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
174 // This can happen when a layout has a left and right margin,
175 // and the view is made very narrow. We can't do better than
176 // to draw it partly out of view (bug 5890).
177 if (mi.base.textwidth < 1)
178 mi.base.textwidth = 1;
181 tm.metrics(mi, dim, mi.base.textwidth);
184 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
185 dim.asc += TEXT_TO_INSET_OFFSET;
186 dim.des += TEXT_TO_INSET_OFFSET;
187 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
191 void InsetText::draw(PainterInfo & pi, int x, int y) const
193 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
195 if (drawFrame_ || pi.full_repaint) {
196 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
197 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
198 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
199 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
201 pi.pain.fillRectangle(xframe, yframe, w, h,
202 pi.backgroundColor(this));
205 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
207 ColorCode const old_color = pi.background_color;
208 pi.background_color = pi.backgroundColor(this, false);
210 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
212 pi.background_color = old_color;
216 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
218 pit_type const pit = front ? 0 : paragraphs().size() - 1;
219 pos_type pos = front ? 0 : paragraphs().back().size();
221 // if visual information is not to be ignored, move to extreme right/left
222 if (entry_from != ENTRY_DIRECTION_IGNORE) {
223 Cursor temp_cur = cur;
224 temp_cur.pit() = pit;
225 temp_cur.pos() = pos;
226 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
227 pos = temp_cur.pos();
230 text_.setCursor(cur.top(), pit, pos);
231 cur.clearSelection();
236 Inset * InsetText::editXY(Cursor & cur, int x, int y)
238 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
242 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
244 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
245 << " [ cmd.action() = " << cmd.action() << ']');
247 if (getLayout().isPassThru()) {
248 // Force any new text to latex_language FIXME: This
249 // should only be necessary in constructor, but new
250 // paragraphs that are created by pressing enter at
251 // the start of an existing paragraph get the buffer
252 // language and not latex_language, so we take this
253 // brute force approach.
254 cur.current_font.setLanguage(latex_language);
255 cur.real_current_font.setLanguage(latex_language);
258 switch (cmd.action()) {
260 case LFUN_CLIPBOARD_PASTE:
261 case LFUN_SELECTION_PASTE:
262 case LFUN_PRIMARY_SELECTION_PASTE:
263 text_.dispatch(cur, cmd);
264 // If we we can only store plain text, we must reset all
266 // FIXME: Change only the pasted paragraphs
270 case LFUN_INSET_DISSOLVE: {
271 bool const main_inset = &buffer().inset() == this;
272 bool const target_inset = cmd.argument().empty()
273 || cmd.getArg(0) == insetName(lyxCode());
274 bool const one_cell = nargs() == 1;
276 if (!main_inset && target_inset && one_cell) {
277 // Text::dissolveInset assumes that the cursor
278 // is inside the Inset.
279 if (&cur.inset() != this)
280 cur.pushBackward(*this);
281 cur.beginUndoGroup();
282 text_.dispatch(cur, cmd);
290 text_.dispatch(cur, cmd);
293 if (!cur.result().dispatched())
294 Inset::doDispatch(cur, cmd);
298 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
299 FuncStatus & status) const
301 switch (cmd.action()) {
302 case LFUN_INSET_DISSOLVE: {
303 bool const main_inset = &buffer().inset() == this;
304 bool const target_inset = cmd.argument().empty()
305 || cmd.getArg(0) == insetName(lyxCode());
306 bool const one_cell = nargs() == 1;
309 status.setEnabled(!main_inset && one_cell);
314 // Dispatch only to text_ if the cursor is inside
315 // the text_. It is not for context menus (bug 5797).
317 if (cur.text() == &text_)
318 ret = text_.getStatus(cur, cmd, status);
321 ret = Inset::getStatus(cur, cmd, status);
327 void InsetText::fixParagraphsFont()
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 if (par->isPassThru())
335 par->resetFonts(font);
336 if (!par->allowParagraphCustomization())
337 par->params().clear();
343 void InsetText::setChange(Change const & change)
345 ParagraphList::iterator pit = paragraphs().begin();
346 ParagraphList::iterator end = paragraphs().end();
347 for (; pit != end; ++pit) {
348 pit->setChange(change);
353 void InsetText::acceptChanges()
355 text_.acceptChanges();
359 void InsetText::rejectChanges()
361 text_.rejectChanges();
365 void InsetText::validate(LaTeXFeatures & features) const
367 features.useInsetLayout(getLayout());
368 for_each(paragraphs().begin(), paragraphs().end(),
369 bind(&Paragraph::validate, _1, ref(features)));
373 void InsetText::latex(otexstream & os, OutputParams const & runparams) const
375 // This implements the standard way of handling the LaTeX
376 // output of a text inset, either a command or an
377 // environment. Standard collapsable insets should not
378 // redefine this, non-standard ones may call this.
379 InsetLayout const & il = getLayout();
380 if (!il.latexname().empty()) {
381 if (il.latextype() == InsetLayout::COMMAND) {
383 if (runparams.moving_arg)
385 os << '\\' << from_utf8(il.latexname());
386 if (!il.latexparam().empty())
387 os << from_utf8(il.latexparam());
389 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
394 if (runparams.lastid != -1)
395 os.texrow().start(runparams.lastid,
397 os << "\\begin{" << from_utf8(il.latexname()) << "}\n";
398 if (!il.latexparam().empty())
399 os << from_utf8(il.latexparam());
402 OutputParams rp = runparams;
405 if (il.isNeedProtect())
406 rp.moving_arg = true;
408 rp.par_end = paragraphs().size();
410 // Output the contents of the inset
411 latexParagraphs(buffer(), text_, os, rp);
412 runparams.encoding = rp.encoding;
414 if (!il.latexname().empty()) {
415 if (il.latextype() == InsetLayout::COMMAND) {
417 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
418 // A comment environment doesn't need a % before \n\end
419 if (il.isDisplay() || runparams.inComment)
423 os << "\\end{" << from_utf8(il.latexname()) << "}\n";
425 os.protectSpace(true);
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(), OutputUpdate);
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 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
546 Paragraph & first = paragraphs().front();
547 for (unsigned int i = 0; i < data.length(); ++i)
548 first.insertChar(i, data[i], font, trackChanges);
552 void InsetText::setAutoBreakRows(bool flag)
554 if (flag == text_.autoBreakRows_)
557 text_.autoBreakRows_ = flag;
561 // remove previously existing newlines
562 ParagraphList::iterator it = paragraphs().begin();
563 ParagraphList::iterator end = paragraphs().end();
564 for (; it != end; ++it)
565 for (int i = 0; i < it->size(); ++i)
566 if (it->isNewline(i))
567 // do not track the change, because the user
568 // is not allowed to revert/reject it
569 it->eraseChar(i, false);
573 void InsetText::setDrawFrame(bool flag)
579 ColorCode InsetText::frameColor() const
585 void InsetText::setFrameColor(ColorCode col)
591 void InsetText::appendParagraphs(ParagraphList & plist)
593 // There is little we can do here to keep track of changes.
594 // As of 2006/10/20, appendParagraphs is used exclusively by
595 // LyXTabular::setMultiColumn. In this context, the paragraph break
596 // is lost irreversibly and the appended text doesn't really change
598 ParagraphList & pl = paragraphs();
600 ParagraphList::iterator pit = plist.begin();
601 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
603 mergeParagraph(buffer().params(), pl,
604 distance(pl.begin(), ins) - 1);
606 for_each(pit, plist.end(),
607 bind(&ParagraphList::push_back, ref(pl), _1));
611 void InsetText::addPreview(DocIterator const & text_inset_pos,
612 PreviewLoader & loader) const
614 ParagraphList::const_iterator pit = paragraphs().begin();
615 ParagraphList::const_iterator pend = paragraphs().end();
618 DocIterator inset_pos = text_inset_pos;
619 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
621 for (; pit != pend; ++pit, ++pidx) {
622 InsetList::const_iterator it = pit->insetList().begin();
623 InsetList::const_iterator end = pit->insetList().end();
624 inset_pos.pit() = pidx;
625 for (; it != end; ++it) {
626 inset_pos.pos() = it->pos;
627 it->inset->addPreview(inset_pos, loader);
633 ParagraphList const & InsetText::paragraphs() const
635 return text_.paragraphs();
639 ParagraphList & InsetText::paragraphs()
641 return text_.paragraphs();
645 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
647 ParIterator it2 = it;
649 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
650 if (producesOutput()) {
651 InsetLayout const & il = getLayout();
652 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
653 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
655 // LYXERR0("Entering " << name());
656 cnt.clearLastLayout();
657 // FIXME cnt.saveLastCounter()?
659 buffer().updateBuffer(it2, utype);
661 // LYXERR0("Exiting " << name());
662 cnt.restoreLastLayout();
663 // FIXME cnt.restoreLastCounter()?
666 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
667 // Note that we do not need to call:
668 // tclass.counters().clearLastLayout()
669 // since we are saving and restoring the existing counters, etc.
670 Counters const savecnt = tclass.counters();
671 tclass.counters().reset();
672 buffer().updateBuffer(it2, utype);
673 tclass.counters() = savecnt;
678 void InsetText::toString(odocstream & os) const
680 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
684 void InsetText::forToc(docstring & os, size_t maxlen) const
686 if (!getLayout().isInToc())
688 text().forToc(os, maxlen, false);
692 void InsetText::addToToc(DocIterator const & cdit) const
694 DocIterator dit = cdit;
695 dit.push_back(CursorSlice(const_cast<InsetText &>(*this)));
696 Toc & toc = buffer().tocBackend().toc("tableofcontents");
698 BufferParams const & bufparams = buffer_->params();
699 int const min_toclevel = bufparams.documentClass().min_toclevel();
701 // For each paragraph, traverse its insets and let them add
703 ParagraphList const & pars = paragraphs();
704 pit_type pend = paragraphs().size();
705 for (pit_type pit = 0; pit != pend; ++pit) {
706 Paragraph const & par = pars[pit];
708 // if we find an optarg, we'll save it for use later.
709 InsetText const * arginset = 0;
710 InsetList::const_iterator it = par.insetList().begin();
711 InsetList::const_iterator end = par.insetList().end();
712 for (; it != end; ++it) {
713 Inset & inset = *it->inset;
715 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
717 if (inset.lyxCode() == ARG_CODE)
718 arginset = inset.asInsetText();
720 // now the toc entry for the paragraph
721 int const toclevel = par.layout().toclevel;
722 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
723 // insert this into the table of contents
726 tocstring = par.labelString();
727 if (!tocstring.empty())
729 arginset->text().forToc(tocstring, TOC_ENTRY_LENGTH);
731 par.forToc(tocstring, TOC_ENTRY_LENGTH);
733 toc.push_back(TocItem(dit, toclevel - min_toclevel,
734 tocstring, tocstring));
737 // And now the list of changes.
738 par.addChangesToToc(dit, buffer());
743 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
745 if (buffer().isClean())
746 return Inset::notifyCursorLeaves(old, cur);
748 // find text inset in old cursor
749 Cursor insetCur = old;
750 int scriptSlice = insetCur.find(this);
751 LASSERT(scriptSlice != -1, /**/);
752 insetCur.cutOff(scriptSlice);
753 LASSERT(&insetCur.inset() == this, /**/);
755 // update the old paragraph's words
756 insetCur.paragraph().updateWords();
758 return Inset::notifyCursorLeaves(old, cur);
762 bool InsetText::completionSupported(Cursor const & cur) const
764 //LASSERT(&cur.bv().cursor().inset() != this, return false);
765 return text_.completionSupported(cur);
769 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
771 return completionSupported(cur);
775 bool InsetText::automaticInlineCompletion() const
777 return lyxrc.completion_inline_text;
781 bool InsetText::automaticPopupCompletion() const
783 return lyxrc.completion_popup_text;
787 bool InsetText::showCompletionCursor() const
789 return lyxrc.completion_cursor_text;
793 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
795 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
799 docstring InsetText::completionPrefix(Cursor const & cur) const
801 if (!completionSupported(cur))
803 return text_.completionPrefix(cur);
807 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
810 if (!completionSupported(cur))
813 return text_.insertCompletion(cur, s, finished);
817 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
818 Dimension & dim) const
820 TextMetrics const & tm = cur.bv().textMetrics(&text_);
821 tm.completionPosAndDim(cur, x, y, dim);
825 docstring InsetText::contextMenu(BufferView const &, int, int) const
827 docstring context_menu = contextMenuName();
828 if (context_menu != InsetText::contextMenuName())
829 context_menu += ";" + InsetText::contextMenuName();
834 docstring InsetText::contextMenuName() const
836 return from_ascii("context-edit");
840 docstring InsetText::toolTipText(docstring prefix,
841 size_t numlines, size_t len) const
843 size_t const max_length = numlines * len;
844 OutputParams rp(&buffer().params().encoding());
845 odocstringstream oss;
848 ParagraphList::const_iterator beg = paragraphs().begin();
849 ParagraphList::const_iterator end = paragraphs().end();
850 ParagraphList::const_iterator it = beg;
851 bool ref_printed = false;
854 for (; it != end; ++it) {
857 writePlaintextParagraph(buffer(), *it, oss, rp, ref_printed);
859 if (str.length() > max_length)
862 return support::wrapParas(str, 4, len, numlines);
866 InsetCaption const * InsetText::getCaptionInset() const
868 ParagraphList::const_iterator pit = paragraphs().begin();
869 for (; pit != paragraphs().end(); ++pit) {
870 InsetList::const_iterator it = pit->insetList().begin();
871 for (; it != pit->insetList().end(); ++it) {
872 Inset & inset = *it->inset;
873 if (inset.lyxCode() == CAPTION_CODE) {
874 InsetCaption const * ins =
875 static_cast<InsetCaption const *>(it->inset);
884 docstring InsetText::getCaptionText(OutputParams const & runparams) const
886 InsetCaption const * ins = getCaptionInset();
890 odocstringstream ods;
891 ins->getCaptionAsPlaintext(ods, runparams);
896 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
898 InsetCaption const * ins = getCaptionInset();
902 odocstringstream ods;
904 docstring def = ins->getCaptionAsHTML(xs, runparams);
906 // should already have been escaped
907 xs << XHTMLStream::ESCAPE_NONE << def << '\n';
912 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
914 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);