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) {
301 case LFUN_INSET_DISSOLVE: {
302 bool const main_inset = &buffer().inset() == this;
303 bool const target_inset = cmd.argument().empty()
304 || cmd.getArg(0) == insetName(lyxCode());
305 bool const one_cell = nargs() == 1;
308 status.setEnabled(!main_inset && one_cell);
313 // Dispatch only to text_ if the cursor is inside
314 // the text_. It is not for context menus (bug 5797).
316 if (cur.text() == &text_)
317 ret = text_.getStatus(cur, cmd, status);
320 ret = Inset::getStatus(cur, cmd, status);
326 void InsetText::fixParagraphsFont()
328 if (!getLayout().isPassThru())
331 Font font(inherit_font, buffer().params().language);
332 font.setLanguage(latex_language);
333 ParagraphList::iterator par = paragraphs().begin();
334 ParagraphList::iterator const end = paragraphs().end();
336 par->resetFonts(font);
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 int InsetText::latex(odocstream & 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();
381 if (!il.latexname().empty()) {
382 if (il.latextype() == InsetLayout::COMMAND) {
384 if (runparams.moving_arg)
386 os << '\\' << from_utf8(il.latexname());
387 if (!il.latexparam().empty())
388 os << from_utf8(il.latexparam());
390 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
391 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
392 if (!il.latexparam().empty())
393 os << from_utf8(il.latexparam());
397 OutputParams rp = runparams;
400 if (il.isNeedProtect())
401 rp.moving_arg = true;
403 // Output the contents of the inset
405 latexParagraphs(buffer(), text_, os, texrow, rp);
406 rows += texrow.rows();
408 if (!il.latexname().empty()) {
409 if (il.latextype() == InsetLayout::COMMAND) {
411 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
412 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
420 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
422 ParagraphList::const_iterator beg = paragraphs().begin();
423 ParagraphList::const_iterator end = paragraphs().end();
424 ParagraphList::const_iterator it = beg;
425 bool ref_printed = false;
427 for (; it != end; ++it) {
430 if (runparams.linelen > 0)
433 odocstringstream oss;
434 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
435 docstring const str = oss.str();
437 // FIXME: len is not computed fully correctly; in principle,
438 // we have to count the characters after the last '\n'
446 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
448 ParagraphList::const_iterator const beg = paragraphs().begin();
451 sgml::openTag(os, getLayout().latexname(),
452 beg->getID(buffer(), runparams) + getLayout().latexparam());
454 docbookParagraphs(text_, buffer(), os, runparams);
457 sgml::closeTag(os, getLayout().latexname());
463 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
465 return insetAsXHTML(xs, runparams, WriteEverything);
470 // There are cases where we may need to close open fonts and such
471 // and then re-open them when we are done. This would be the case, e.g.,
472 // if we were otherwise about to write:
473 // <em>word <div class='foot'>footnote text.</div> emph</em>
474 // The problem isn't so much that the footnote text will get emphasized:
475 // we can handle that with CSS. The problem is that this is invalid XHTML.
476 // One solution would be to make the footnote <span>, but the problem is
477 // completely general, and so we'd have to make absolutely everything into
478 // span. What I think will work is to check if we're about to write "div" and,
479 // if so, try to close fonts, etc.
480 // There are probably limits to how well we can do here, though, and we will
481 // have to rely upon users not putting footnotes inside noun-type insets.
482 docstring InsetText::insetAsXHTML(XHTMLStream & xs, OutputParams const & runparams,
483 XHTMLOptions opts) const
486 xhtmlParagraphs(text_, buffer(), xs, runparams);
490 InsetLayout const & il = getLayout();
491 if (opts & WriteOuterTag)
492 xs << html::StartTag(il.htmltag(), il.htmlattr());
493 if ((opts & WriteLabel) && !il.counter().empty()) {
494 BufferParams const & bp = buffer().masterBuffer()->params();
495 Counters & cntrs = bp.documentClass().counters();
496 cntrs.step(il.counter(), OutputUpdate);
497 // FIXME: translate to paragraph language
498 if (!il.htmllabel().empty()) {
499 docstring const lbl =
500 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
501 // FIXME is this check necessary?
503 xs << html::StartTag(il.htmllabeltag(), il.htmllabelattr());
505 xs << html::EndTag(il.htmllabeltag());
510 if (opts & WriteInnerTag)
511 xs << html::StartTag(il.htmlinnertag(), il.htmlinnerattr());
512 OutputParams ours = runparams;
513 if (!il.isMultiPar() || opts == JustText)
514 ours.html_make_pars = false;
515 xhtmlParagraphs(text_, buffer(), xs, ours);
516 if (opts & WriteInnerTag)
517 xs << html::EndTag(il.htmlinnertag());
518 if (opts & WriteOuterTag)
519 xs << html::EndTag(il.htmltag());
524 void InsetText::cursorPos(BufferView const & bv,
525 CursorSlice const & sl, bool boundary, int & x, int & y) const
527 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
528 y = bv.textMetrics(&text_).cursorY(sl, boundary);
532 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
535 Paragraph & first = paragraphs().front();
536 for (unsigned int i = 0; i < data.length(); ++i)
537 first.insertChar(i, data[i], font, trackChanges);
541 void InsetText::setAutoBreakRows(bool flag)
543 if (flag == text_.autoBreakRows_)
546 text_.autoBreakRows_ = flag;
550 // remove previously existing newlines
551 ParagraphList::iterator it = paragraphs().begin();
552 ParagraphList::iterator end = paragraphs().end();
553 for (; it != end; ++it)
554 for (int i = 0; i < it->size(); ++i)
555 if (it->isNewline(i))
556 // do not track the change, because the user
557 // is not allowed to revert/reject it
558 it->eraseChar(i, false);
562 void InsetText::setDrawFrame(bool flag)
568 ColorCode InsetText::frameColor() const
574 void InsetText::setFrameColor(ColorCode col)
580 void InsetText::appendParagraphs(ParagraphList & plist)
582 // There is little we can do here to keep track of changes.
583 // As of 2006/10/20, appendParagraphs is used exclusively by
584 // LyXTabular::setMultiColumn. In this context, the paragraph break
585 // is lost irreversibly and the appended text doesn't really change
587 ParagraphList & pl = paragraphs();
589 ParagraphList::iterator pit = plist.begin();
590 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
592 mergeParagraph(buffer().params(), pl,
593 distance(pl.begin(), ins) - 1);
595 for_each(pit, plist.end(),
596 bind(&ParagraphList::push_back, ref(pl), _1));
600 void InsetText::addPreview(DocIterator const & text_inset_pos,
601 PreviewLoader & loader) const
603 ParagraphList::const_iterator pit = paragraphs().begin();
604 ParagraphList::const_iterator pend = paragraphs().end();
607 DocIterator inset_pos = text_inset_pos;
608 inset_pos.push_back(CursorSlice(*const_cast<InsetText *>(this)));
610 for (; pit != pend; ++pit, ++pidx) {
611 InsetList::const_iterator it = pit->insetList().begin();
612 InsetList::const_iterator end = pit->insetList().end();
613 inset_pos.pit() = pidx;
614 for (; it != end; ++it) {
615 inset_pos.pos() = it->pos;
616 it->inset->addPreview(inset_pos, loader);
622 ParagraphList const & InsetText::paragraphs() const
624 return text_.paragraphs();
628 ParagraphList & InsetText::paragraphs()
630 return text_.paragraphs();
634 void InsetText::updateBuffer(ParIterator const & it, UpdateType utype)
636 ParIterator it2 = it;
638 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
639 if (producesOutput()) {
640 InsetLayout const & il = getLayout();
641 bool const save_layouts = utype == OutputUpdate && il.htmlisblock();
642 Counters & cnt = buffer().masterBuffer()->params().documentClass().counters();
644 // LYXERR0("Entering " << name());
645 cnt.clearLastLayout();
646 // FIXME cnt.saveLastCounter()?
648 buffer().updateBuffer(it2, utype);
650 // LYXERR0("Exiting " << name());
651 cnt.restoreLastLayout();
652 // FIXME cnt.restoreLastCounter()?
655 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
656 // Note that we do not need to call:
657 // tclass.counters().clearLastLayout()
658 // since we are saving and restoring the existing counters, etc.
659 Counters const savecnt = tclass.counters();
660 buffer().updateBuffer(it2, utype);
661 tclass.counters() = savecnt;
666 void InsetText::tocString(odocstream & os) const
668 if (!getLayout().isInToc())
670 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
675 void InsetText::addToToc(DocIterator const & cdit)
677 DocIterator dit = cdit;
678 dit.push_back(CursorSlice(*this));
679 Toc & toc = buffer().tocBackend().toc("tableofcontents");
681 BufferParams const & bufparams = buffer_->params();
682 const int min_toclevel = bufparams.documentClass().min_toclevel();
684 // For each paragraph, traverse its insets and let them add
686 ParagraphList & pars = paragraphs();
687 pit_type pend = paragraphs().size();
688 for (pit_type pit = 0; pit != pend; ++pit) {
689 Paragraph const & par = pars[pit];
691 // the string that goes to the toc (could be the optarg)
693 InsetList::const_iterator it = par.insetList().begin();
694 InsetList::const_iterator end = par.insetList().end();
695 for (; it != end; ++it) {
696 Inset & inset = *it->inset;
698 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
700 switch (inset.lyxCode()) {
702 if (!tocstring.empty())
705 Paragraph const & insetpar =
706 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
707 if (!par.labelString().empty())
708 tocstring = par.labelString() + ' ';
709 tocstring += insetpar.asString(AS_STR_INSETS);
716 // now the toc entry for the paragraph
717 int const toclevel = par.layout().toclevel;
718 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
720 // insert this into the table of contents
721 if (tocstring.empty())
722 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
723 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
726 // And now the list of changes.
727 par.addChangesToToc(dit, buffer());
732 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
734 if (buffer().isClean())
735 return Inset::notifyCursorLeaves(old, cur);
737 // find text inset in old cursor
738 Cursor insetCur = old;
739 int scriptSlice = insetCur.find(this);
740 LASSERT(scriptSlice != -1, /**/);
741 insetCur.cutOff(scriptSlice);
742 LASSERT(&insetCur.inset() == this, /**/);
744 // update the old paragraph's words
745 insetCur.paragraph().updateWords();
747 return Inset::notifyCursorLeaves(old, cur);
751 bool InsetText::completionSupported(Cursor const & cur) const
753 //LASSERT(&cur.bv().cursor().inset() != this, return false);
754 return text_.completionSupported(cur);
758 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
760 return completionSupported(cur);
764 bool InsetText::automaticInlineCompletion() const
766 return lyxrc.completion_inline_text;
770 bool InsetText::automaticPopupCompletion() const
772 return lyxrc.completion_popup_text;
776 bool InsetText::showCompletionCursor() const
778 return lyxrc.completion_cursor_text;
782 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
784 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
788 docstring InsetText::completionPrefix(Cursor const & cur) const
790 if (!completionSupported(cur))
792 return text_.completionPrefix(cur);
796 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
799 if (!completionSupported(cur))
802 return text_.insertCompletion(cur, s, finished);
806 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
807 Dimension & dim) const
809 TextMetrics const & tm = cur.bv().textMetrics(&text_);
810 tm.completionPosAndDim(cur, x, y, dim);
814 docstring InsetText::contextMenu(BufferView const &, int, int) const
816 return from_ascii("context-edit");
820 InsetCaption const * InsetText::getCaptionInset() const
822 ParagraphList::const_iterator pit = paragraphs().begin();
823 for (; pit != paragraphs().end(); ++pit) {
824 InsetList::const_iterator it = pit->insetList().begin();
825 for (; it != pit->insetList().end(); ++it) {
826 Inset & inset = *it->inset;
827 if (inset.lyxCode() == CAPTION_CODE) {
828 InsetCaption const * ins =
829 static_cast<InsetCaption const *>(it->inset);
838 docstring InsetText::getCaptionText(OutputParams const & runparams) const
840 InsetCaption const * ins = getCaptionInset();
844 odocstringstream ods;
845 ins->getCaptionAsPlaintext(ods, runparams);
850 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
852 InsetCaption const * ins = getCaptionInset();
856 odocstringstream ods;
858 docstring def = ins->getCaptionAsHTML(xs, runparams);
860 // should already have been escaped
861 xs << XHTMLStream::NextRaw() << def << '\n';
866 InsetText::XHTMLOptions operator|(InsetText::XHTMLOptions a1, InsetText::XHTMLOptions a2)
868 return static_cast<InsetText::XHTMLOptions>((int)a1 | (int)a2);