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), text_(this)
84 InsetText::InsetText(InsetText const & in)
85 : Inset(in), text_(this)
87 text_.autoBreakRows_ = in.text_.autoBreakRows_;
88 drawFrame_ = in.drawFrame_;
89 frame_color_ = in.frame_color_;
90 text_.paragraphs() = in.text_.paragraphs();
95 void InsetText::setBuffer(Buffer & buf)
97 ParagraphList::iterator end = paragraphs().end();
98 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100 Inset::setBuffer(buf);
104 void InsetText::initParagraphs(UsePlain type)
106 LASSERT(paragraphs().empty(), /**/);
107 paragraphs().push_back(Paragraph());
108 Paragraph & ourpar = paragraphs().back();
109 ourpar.setInsetOwner(this);
110 DocumentClass const & dc = buffer_->params().documentClass();
111 if (type == DefaultLayout)
112 ourpar.setDefaultLayout(dc);
114 ourpar.setPlainLayout(dc);
118 void InsetText::setParagraphOwner()
120 for_each(paragraphs().begin(), paragraphs().end(),
121 bind(&Paragraph::setInsetOwner, _1, this));
125 void InsetText::clear()
127 ParagraphList & pars = paragraphs();
128 LASSERT(!pars.empty(), /**/);
130 // This is a gross hack...
131 Layout const & old_layout = pars.begin()->layout();
134 pars.push_back(Paragraph());
135 pars.begin()->setInsetOwner(this);
136 pars.begin()->setLayout(old_layout);
140 Dimension const InsetText::dimension(BufferView const & bv) const
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;
151 void InsetText::write(ostream & os) const
158 void InsetText::read(Lexer & lex)
162 // delete the initial paragraph
163 Paragraph oldpar = *paragraphs().begin();
164 paragraphs().clear();
166 lex.setContext("InsetText::read");
167 bool res = text_.read(lex, errorList, this);
170 lex.printError("Missing \\end_inset at this point. ");
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.
187 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193 // Hand font through to contained lyxtext:
194 tm.font_.fontInfo() = mi.base.font;
195 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
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;
204 tm.metrics(mi, dim, mi.base.textwidth);
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;
214 void InsetText::draw(PainterInfo & pi, int x, int y) const
216 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
218 if (drawFrame_ || pi.full_repaint) {
219 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
220 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
221 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
222 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
224 pi.pain.fillRectangle(xframe, yframe, w, h,
225 pi.backgroundColor(this));
228 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
230 ColorCode const old_color = pi.background_color;
231 pi.background_color = pi.backgroundColor(this, false);
233 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
235 pi.background_color = old_color;
239 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
241 pit_type const pit = front ? 0 : paragraphs().size() - 1;
242 pos_type pos = front ? 0 : paragraphs().back().size();
244 // if visual information is not to be ignored, move to extreme right/left
245 if (entry_from != ENTRY_DIRECTION_IGNORE) {
246 Cursor temp_cur = cur;
247 temp_cur.pit() = pit;
248 temp_cur.pos() = pos;
249 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
250 pos = temp_cur.pos();
253 text_.setCursor(cur.top(), pit, pos);
254 cur.clearSelection();
259 Inset * InsetText::editXY(Cursor & cur, int x, int y)
261 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
265 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
267 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
268 << " [ cmd.action = " << cmd.action << ']');
270 if (getLayout().isPassThru()) {
271 // Force any new text to latex_language FIXME: This
272 // should only be necessary in constructor, but new
273 // paragraphs that are created by pressing enter at
274 // the start of an existing paragraph get the buffer
275 // language and not latex_language, so we take this
276 // brute force approach.
277 cur.current_font.setLanguage(latex_language);
278 cur.real_current_font.setLanguage(latex_language);
281 switch (cmd.action) {
283 case LFUN_CLIPBOARD_PASTE:
284 case LFUN_SELECTION_PASTE:
285 case LFUN_PRIMARY_SELECTION_PASTE:
286 text_.dispatch(cur, cmd);
287 // If we we can only store plain text, we must reset all
289 // FIXME: Change only the pasted paragraphs
293 case LFUN_INSET_DISSOLVE: {
294 bool const main_inset = &buffer().inset() == this;
295 bool const target_inset = cmd.argument().empty()
296 || cmd.getArg(0) == insetName(lyxCode());
297 bool const one_cell = nargs() == 1;
299 if (!main_inset && target_inset && one_cell) {
300 // Text::dissolveInset assumes that the cursor
301 // is inside the Inset.
302 if (&cur.inset() != this)
303 cur.pushBackward(*this);
304 cur.beginUndoGroup();
305 text_.dispatch(cur, cmd);
313 text_.dispatch(cur, cmd);
316 if (!cur.result().dispatched())
317 Inset::doDispatch(cur, cmd);
321 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
322 FuncStatus & status) const
324 switch (cmd.action) {
326 status.setEnabled(!forcePlainLayout());
329 case LFUN_LAYOUT_PARAGRAPH:
330 case LFUN_PARAGRAPH_PARAMS:
331 case LFUN_PARAGRAPH_PARAMS_APPLY:
332 case LFUN_PARAGRAPH_UPDATE:
333 status.setEnabled(allowParagraphCustomization());
336 case LFUN_INSET_DISSOLVE: {
337 bool const main_inset = &buffer().inset() == this;
338 bool const target_inset = cmd.argument().empty()
339 || cmd.getArg(0) == insetName(lyxCode());
340 bool const one_cell = nargs() == 1;
343 status.setEnabled(!main_inset && one_cell);
348 // Dispatch only to text_ if the cursor is inside
349 // the text_. It is not for context menus (bug 5797).
351 if (cur.text() == &text_)
352 ret = text_.getStatus(cur, cmd, status);
355 ret = Inset::getStatus(cur, cmd, status);
361 void InsetText::fixParagraphsFont()
363 if (!getLayout().isPassThru())
366 Font font(inherit_font, buffer().params().language);
367 font.setLanguage(latex_language);
368 ParagraphList::iterator par = paragraphs().begin();
369 ParagraphList::iterator const end = paragraphs().end();
371 par->resetFonts(font);
372 par->params().clear();
378 void InsetText::setChange(Change const & change)
380 ParagraphList::iterator pit = paragraphs().begin();
381 ParagraphList::iterator end = paragraphs().end();
382 for (; pit != end; ++pit) {
383 pit->setChange(change);
388 void InsetText::acceptChanges()
390 text_.acceptChanges();
394 void InsetText::rejectChanges()
396 text_.rejectChanges();
400 void InsetText::validate(LaTeXFeatures & features) const
402 features.useInsetLayout(getLayout());
403 for_each(paragraphs().begin(), paragraphs().end(),
404 bind(&Paragraph::validate, _1, ref(features)));
408 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
410 // This implements the standard way of handling the LaTeX
411 // output of a text inset, either a command or an
412 // environment. Standard collapsable insets should not
413 // redefine this, non-standard ones may call this.
414 InsetLayout const & il = getLayout();
416 if (!il.latexname().empty()) {
417 if (il.latextype() == InsetLayout::COMMAND) {
419 if (runparams.moving_arg)
421 os << '\\' << from_utf8(il.latexname());
422 if (!il.latexparam().empty())
423 os << from_utf8(il.latexparam());
425 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
426 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
427 if (!il.latexparam().empty())
428 os << from_utf8(il.latexparam());
432 OutputParams rp = runparams;
435 if (il.isNeedProtect())
436 rp.moving_arg = true;
438 // Output the contents of the inset
440 latexParagraphs(buffer(), text_, os, texrow, rp);
441 rows += texrow.rows();
443 if (!il.latexname().empty()) {
444 if (il.latextype() == InsetLayout::COMMAND) {
446 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
447 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
455 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
457 ParagraphList::const_iterator beg = paragraphs().begin();
458 ParagraphList::const_iterator end = paragraphs().end();
459 ParagraphList::const_iterator it = beg;
460 bool ref_printed = false;
462 for (; it != end; ++it) {
465 if (runparams.linelen > 0)
468 odocstringstream oss;
469 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
470 docstring const str = oss.str();
472 // FIXME: len is not computed fully correctly; in principle,
473 // we have to count the characters after the last '\n'
481 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
483 ParagraphList::const_iterator const beg = paragraphs().begin();
486 sgml::openTag(os, getLayout().latexname(),
487 beg->getID(buffer(), runparams) + getLayout().latexparam());
489 docbookParagraphs(text_, buffer(), os, runparams);
492 sgml::closeTag(os, getLayout().latexname());
498 docstring InsetText::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
501 xhtmlParagraphs(text_, buffer(), xs, runparams);
505 InsetLayout const & il = getLayout();
506 xs << StartTag(il.htmltag(), il.htmlattr());
507 if (!il.counter().empty()) {
508 BufferParams const & bp = buffer().masterBuffer()->params();
509 Counters & cntrs = bp.documentClass().counters();
510 cntrs.step(il.counter());
511 // FIXME: translate to paragraph language
512 if (!il.htmllabel().empty()) {
513 docstring const lbl =
514 cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
515 // FIXME is this check necessary?
517 xs << StartTag(il.htmllabeltag(), il.htmllabelattr());
519 xs << EndTag(il.htmllabeltag());
524 xs << StartTag(il.htmlinnertag(), il.htmlinnerattr());
526 xhtmlParagraphs(text_, buffer(), xs, runparams);
528 OutputParams ours = runparams;
529 ours.html_make_pars = false;
530 xhtmlParagraphs(text_, buffer(), xs, ours);
532 xs << EndTag(il.htmlinnertag());
533 xs << EndTag(il.htmltag());
538 void InsetText::cursorPos(BufferView const & bv,
539 CursorSlice const & sl, bool boundary, int & x, int & y) const
541 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
542 y = bv.textMetrics(&text_).cursorY(sl, boundary);
546 bool InsetText::showInsetDialog(BufferView *) const
552 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
555 Paragraph & first = paragraphs().front();
556 for (unsigned int i = 0; i < data.length(); ++i)
557 first.insertChar(i, data[i], font, trackChanges);
561 void InsetText::setAutoBreakRows(bool flag)
563 if (flag == text_.autoBreakRows_)
566 text_.autoBreakRows_ = flag;
570 // remove previously existing newlines
571 ParagraphList::iterator it = paragraphs().begin();
572 ParagraphList::iterator end = paragraphs().end();
573 for (; it != end; ++it)
574 for (int i = 0; i < it->size(); ++i)
575 if (it->isNewline(i))
576 // do not track the change, because the user
577 // is not allowed to revert/reject it
578 it->eraseChar(i, false);
582 void InsetText::setDrawFrame(bool flag)
588 ColorCode InsetText::frameColor() const
594 void InsetText::setFrameColor(ColorCode col)
600 void InsetText::appendParagraphs(ParagraphList & plist)
602 // There is little we can do here to keep track of changes.
603 // As of 2006/10/20, appendParagraphs is used exclusively by
604 // LyXTabular::setMultiColumn. In this context, the paragraph break
605 // is lost irreversibly and the appended text doesn't really change
607 ParagraphList & pl = paragraphs();
609 ParagraphList::iterator pit = plist.begin();
610 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
612 mergeParagraph(buffer().params(), pl,
613 distance(pl.begin(), ins) - 1);
615 for_each(pit, plist.end(),
616 bind(&ParagraphList::push_back, ref(pl), _1));
620 void InsetText::addPreview(PreviewLoader & loader) const
622 ParagraphList::const_iterator pit = paragraphs().begin();
623 ParagraphList::const_iterator pend = paragraphs().end();
625 for (; pit != pend; ++pit) {
626 InsetList::const_iterator it = pit->insetList().begin();
627 InsetList::const_iterator end = pit->insetList().end();
628 for (; it != end; ++it)
629 it->inset->addPreview(loader);
634 ParagraphList const & InsetText::paragraphs() const
636 return text_.paragraphs();
640 ParagraphList & InsetText::paragraphs()
642 return text_.paragraphs();
646 void InsetText::updateLabels(ParIterator const & it)
648 ParIterator it2 = it;
650 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
651 if (producesOutput())
652 buffer().updateLabels(it2);
654 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
655 Counters const savecnt = tclass.counters();
656 buffer().updateLabels(it2);
657 tclass.counters() = savecnt;
662 void InsetText::tocString(odocstream & os) const
664 if (!getLayout().isInToc())
666 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
671 void InsetText::addToToc(DocIterator const & cdit)
673 DocIterator dit = cdit;
674 dit.push_back(CursorSlice(*this));
675 Toc & toc = buffer().tocBackend().toc("tableofcontents");
677 BufferParams const & bufparams = buffer_->params();
678 const int min_toclevel = bufparams.documentClass().min_toclevel();
680 // For each paragraph, traverse its insets and let them add
682 ParagraphList & pars = paragraphs();
683 pit_type pend = paragraphs().size();
684 for (pit_type pit = 0; pit != pend; ++pit) {
685 Paragraph const & par = pars[pit];
687 // the string that goes to the toc (could be the optarg)
689 InsetList::const_iterator it = par.insetList().begin();
690 InsetList::const_iterator end = par.insetList().end();
691 for (; it != end; ++it) {
692 Inset & inset = *it->inset;
694 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
696 switch (inset.lyxCode()) {
698 if (!tocstring.empty())
701 Paragraph const & insetpar =
702 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
703 if (!par.labelString().empty())
704 tocstring = par.labelString() + ' ';
705 tocstring += insetpar.asString(AS_STR_INSETS);
712 // now the toc entry for the paragraph
713 int const toclevel = par.layout().toclevel;
714 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
716 // insert this into the table of contents
717 if (tocstring.empty())
718 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
719 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
722 // And now the list of changes.
723 par.addChangesToToc(dit, buffer());
728 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
730 if (buffer().isClean())
731 return Inset::notifyCursorLeaves(old, cur);
733 // find text inset in old cursor
734 Cursor insetCur = old;
735 int scriptSlice = insetCur.find(this);
736 LASSERT(scriptSlice != -1, /**/);
737 insetCur.cutOff(scriptSlice);
738 LASSERT(&insetCur.inset() == this, /**/);
740 // update the old paragraph's words
741 insetCur.paragraph().updateWords();
743 return Inset::notifyCursorLeaves(old, cur);
747 bool InsetText::completionSupported(Cursor const & cur) const
749 //LASSERT(&cur.bv().cursor().inset() != this, return false);
750 return text_.completionSupported(cur);
754 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
756 return completionSupported(cur);
760 bool InsetText::automaticInlineCompletion() const
762 return lyxrc.completion_inline_text;
766 bool InsetText::automaticPopupCompletion() const
768 return lyxrc.completion_popup_text;
772 bool InsetText::showCompletionCursor() const
774 return lyxrc.completion_cursor_text;
778 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
780 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
784 docstring InsetText::completionPrefix(Cursor const & cur) const
786 if (!completionSupported(cur))
788 return text_.completionPrefix(cur);
792 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
795 if (!completionSupported(cur))
798 return text_.insertCompletion(cur, s, finished);
802 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
803 Dimension & dim) const
805 TextMetrics const & tm = cur.bv().textMetrics(&text_);
806 tm.completionPosAndDim(cur, x, y, dim);
810 docstring InsetText::contextMenu(BufferView const &, int, int) const
812 return from_ascii("context-edit");
816 InsetCaption const * InsetText::getCaptionInset() const
818 ParagraphList::const_iterator pit = paragraphs().begin();
819 for (; pit != paragraphs().end(); ++pit) {
820 InsetList::const_iterator it = pit->insetList().begin();
821 for (; it != pit->insetList().end(); ++it) {
822 Inset & inset = *it->inset;
823 if (inset.lyxCode() == CAPTION_CODE) {
824 InsetCaption const * ins =
825 static_cast<InsetCaption const *>(it->inset);
834 docstring InsetText::getCaptionText(OutputParams const & runparams) const
836 InsetCaption const * ins = getCaptionInset();
840 odocstringstream ods;
841 ins->getCaptionAsPlaintext(ods, runparams);
846 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
848 InsetCaption const * ins = getCaptionInset();
852 odocstringstream ods;
853 docstring def = ins->getCaptionAsHTML(ods, runparams);