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 const & buf, UsePlain type)
78 : drawFrame_(false), frame_color_(Color_insetframe), text_(this)
80 setBuffer(const_cast<Buffer &>(buf));
85 InsetText::InsetText(InsetText const & in)
86 : Inset(in), text_(this)
88 text_.autoBreakRows_ = in.text_.autoBreakRows_;
89 drawFrame_ = in.drawFrame_;
90 frame_color_ = in.frame_color_;
91 text_.paragraphs() = in.text_.paragraphs();
96 void InsetText::setBuffer(Buffer & buf)
98 ParagraphList::iterator end = paragraphs().end();
99 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
101 Inset::setBuffer(buf);
105 void InsetText::initParagraphs(UsePlain type)
107 LASSERT(paragraphs().empty(), /**/);
108 paragraphs().push_back(Paragraph());
109 Paragraph & ourpar = paragraphs().back();
110 ourpar.setInsetOwner(this);
111 DocumentClass const & dc = buffer_->params().documentClass();
112 if (type == DefaultLayout)
113 ourpar.setDefaultLayout(dc);
115 ourpar.setPlainLayout(dc);
119 void InsetText::setParagraphOwner()
121 for_each(paragraphs().begin(), paragraphs().end(),
122 bind(&Paragraph::setInsetOwner, _1, this));
126 void InsetText::clear()
128 ParagraphList & pars = paragraphs();
129 LASSERT(!pars.empty(), /**/);
131 // This is a gross hack...
132 Layout const & old_layout = pars.begin()->layout();
135 pars.push_back(Paragraph());
136 pars.begin()->setInsetOwner(this);
137 pars.begin()->setLayout(old_layout);
141 Dimension const InsetText::dimension(BufferView const & bv) const
143 TextMetrics const & tm = bv.textMetrics(&text_);
144 Dimension dim = tm.dimension();
145 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
146 dim.des += TEXT_TO_INSET_OFFSET;
147 dim.asc += TEXT_TO_INSET_OFFSET;
152 void InsetText::write(ostream & os) const
159 void InsetText::read(Lexer & lex)
163 // delete the initial paragraph
164 Paragraph oldpar = *paragraphs().begin();
165 paragraphs().clear();
167 lex.setContext("InsetText::read");
168 bool res = text_.read(lex, errorList, this);
171 lex.printError("Missing \\end_inset at this point. ");
174 // ensure we have at least one paragraph.
175 if (paragraphs().empty())
176 paragraphs().push_back(oldpar);
177 // Force default font, if so requested
178 // This avoids paragraphs in buffer language that would have a
179 // foreign language after a document language change, and it ensures
180 // that all new text in ERT and similar gets the "latex" language,
181 // since new text inherits the language from the last position of the
182 // existing text. As a side effect this makes us also robust against
183 // bugs in LyX that might lead to font changes in ERT in .lyx files.
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
190 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
192 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
194 // Hand font through to contained lyxtext:
195 tm.font_.fontInfo() = mi.base.font;
196 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
198 // This can happen when a layout has a left and right margin,
199 // and the view is made very narrow. We can't do better than
200 // to draw it partly out of view (bug 5890).
201 if (mi.base.textwidth < 1)
202 mi.base.textwidth = 1;
205 tm.metrics(mi, dim, mi.base.textwidth);
208 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
209 dim.asc += TEXT_TO_INSET_OFFSET;
210 dim.des += TEXT_TO_INSET_OFFSET;
211 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
215 void InsetText::draw(PainterInfo & pi, int x, int y) const
217 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
219 if (drawFrame_ || pi.full_repaint) {
220 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
221 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
222 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
223 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
225 pi.pain.fillRectangle(xframe, yframe, w, h,
226 pi.backgroundColor(this));
229 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
231 ColorCode const old_color = pi.background_color;
232 pi.background_color = pi.backgroundColor(this, false);
234 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
236 pi.background_color = old_color;
240 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
242 pit_type const pit = front ? 0 : paragraphs().size() - 1;
243 pos_type pos = front ? 0 : paragraphs().back().size();
245 // if visual information is not to be ignored, move to extreme right/left
246 if (entry_from != ENTRY_DIRECTION_IGNORE) {
247 Cursor temp_cur = cur;
248 temp_cur.pit() = pit;
249 temp_cur.pos() = pos;
250 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
251 pos = temp_cur.pos();
254 text_.setCursor(cur.top(), pit, pos);
255 cur.clearSelection();
260 Inset * InsetText::editXY(Cursor & cur, int x, int y)
262 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
266 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
268 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
269 << " [ cmd.action = " << cmd.action << ']');
271 if (getLayout().isPassThru()) {
272 // Force any new text to latex_language FIXME: This
273 // should only be necessary in constructor, but new
274 // paragraphs that are created by pressing enter at
275 // the start of an existing paragraph get the buffer
276 // language and not latex_language, so we take this
277 // brute force approach.
278 cur.current_font.setLanguage(latex_language);
279 cur.real_current_font.setLanguage(latex_language);
282 switch (cmd.action) {
284 case LFUN_CLIPBOARD_PASTE:
285 case LFUN_SELECTION_PASTE:
286 case LFUN_PRIMARY_SELECTION_PASTE:
287 text_.dispatch(cur, cmd);
288 // If we we can only store plain text, we must reset all
290 // FIXME: Change only the pasted paragraphs
294 text_.dispatch(cur, cmd);
297 if (!cur.result().dispatched())
298 Inset::doDispatch(cur, cmd);
302 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
303 FuncStatus & status) const
305 switch (cmd.action) {
307 status.setEnabled(!forcePlainLayout());
310 case LFUN_LAYOUT_PARAGRAPH:
311 case LFUN_PARAGRAPH_PARAMS:
312 case LFUN_PARAGRAPH_PARAMS_APPLY:
313 case LFUN_PARAGRAPH_UPDATE:
314 status.setEnabled(allowParagraphCustomization());
317 // Dispatch only to text_ if the cursor is inside
318 // the text_. It is not for context menus (bug 5797).
320 if (cur.text() == &text_)
321 ret = text_.getStatus(cur, cmd, status);
324 ret = Inset::getStatus(cur, cmd, status);
330 void InsetText::fixParagraphsFont()
332 if (!getLayout().isPassThru())
335 Font font(inherit_font, buffer().params().language);
336 font.setLanguage(latex_language);
337 ParagraphList::iterator par = paragraphs().begin();
338 ParagraphList::iterator const end = paragraphs().end();
340 par->resetFonts(font);
341 par->params().clear();
347 void InsetText::setChange(Change const & change)
349 ParagraphList::iterator pit = paragraphs().begin();
350 ParagraphList::iterator end = paragraphs().end();
351 for (; pit != end; ++pit) {
352 pit->setChange(change);
357 void InsetText::acceptChanges()
359 text_.acceptChanges();
363 void InsetText::rejectChanges()
365 text_.rejectChanges();
369 void InsetText::validate(LaTeXFeatures & features) const
371 features.useInsetLayout(getLayout());
372 for_each(paragraphs().begin(), paragraphs().end(),
373 bind(&Paragraph::validate, _1, ref(features)));
377 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
379 // This implements the standard way of handling the LaTeX
380 // output of a text inset, either a command or an
381 // environment. Standard collapsable insets should not
382 // redefine this, non-standard ones may call this.
383 InsetLayout const & il = getLayout();
385 if (!il.latexname().empty()) {
386 if (il.latextype() == InsetLayout::COMMAND) {
388 if (runparams.moving_arg)
390 os << '\\' << from_utf8(il.latexname());
391 if (!il.latexparam().empty())
392 os << from_utf8(il.latexparam());
394 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
395 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
396 if (!il.latexparam().empty())
397 os << from_utf8(il.latexparam());
401 OutputParams rp = runparams;
404 if (il.isNeedProtect())
405 rp.moving_arg = true;
407 // Output the contents of the inset
409 latexParagraphs(buffer(), text_, os, texrow, rp);
410 rows += texrow.rows();
412 if (!il.latexname().empty()) {
413 if (il.latextype() == InsetLayout::COMMAND) {
415 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
416 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
424 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
426 ParagraphList::const_iterator beg = paragraphs().begin();
427 ParagraphList::const_iterator end = paragraphs().end();
428 ParagraphList::const_iterator it = beg;
429 bool ref_printed = false;
431 for (; it != end; ++it) {
434 if (runparams.linelen > 0)
437 odocstringstream oss;
438 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
439 docstring const str = oss.str();
441 // FIXME: len is not computed fully correctly; in principle,
442 // we have to count the characters after the last '\n'
450 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
452 ParagraphList::const_iterator const beg = paragraphs().begin();
455 sgml::openTag(os, getLayout().latexname(),
456 beg->getID(buffer(), runparams) + getLayout().latexparam());
458 docbookParagraphs(text_, buffer(), os, runparams);
461 sgml::closeTag(os, getLayout().latexname());
467 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
469 InsetLayout const & il = getLayout();
471 xhtmlParagraphs(text_, buffer(), os, runparams);
475 bool const opened = html::openTag(os, il.htmltag(), il.htmlattr());
476 if (!il.counter().empty()) {
477 BufferParams const & bp = buffer().masterBuffer()->params();
478 Counters & cntrs = bp.documentClass().counters();
479 cntrs.step(il.counter());
480 // FIXME: translate to paragraph language
481 if (!il.htmllabel().empty())
482 os << cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
484 bool innertag_opened = false;
485 if (!il.htmlinnertag().empty())
486 innertag_opened = html::openTag(os, il.htmlinnertag(), il.htmlinnerattr());
488 xhtmlParagraphs(text_, buffer(), os, runparams);
491 html::closeTag(os, il.htmlinnertag());
493 html::closeTag(os, il.htmltag());
498 void InsetText::cursorPos(BufferView const & bv,
499 CursorSlice const & sl, bool boundary, int & x, int & y) const
501 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
502 y = bv.textMetrics(&text_).cursorY(sl, boundary);
506 bool InsetText::showInsetDialog(BufferView *) const
512 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
515 Paragraph & first = paragraphs().front();
516 for (unsigned int i = 0; i < data.length(); ++i)
517 first.insertChar(i, data[i], font, trackChanges);
521 void InsetText::setAutoBreakRows(bool flag)
523 if (flag == text_.autoBreakRows_)
526 text_.autoBreakRows_ = flag;
530 // remove previously existing newlines
531 ParagraphList::iterator it = paragraphs().begin();
532 ParagraphList::iterator end = paragraphs().end();
533 for (; it != end; ++it)
534 for (int i = 0; i < it->size(); ++i)
535 if (it->isNewline(i))
536 // do not track the change, because the user
537 // is not allowed to revert/reject it
538 it->eraseChar(i, false);
542 void InsetText::setDrawFrame(bool flag)
548 ColorCode InsetText::frameColor() const
554 void InsetText::setFrameColor(ColorCode col)
560 void InsetText::appendParagraphs(ParagraphList & plist)
562 // There is little we can do here to keep track of changes.
563 // As of 2006/10/20, appendParagraphs is used exclusively by
564 // LyXTabular::setMultiColumn. In this context, the paragraph break
565 // is lost irreversibly and the appended text doesn't really change
567 ParagraphList & pl = paragraphs();
569 ParagraphList::iterator pit = plist.begin();
570 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
572 mergeParagraph(buffer().params(), pl,
573 distance(pl.begin(), ins) - 1);
575 for_each(pit, plist.end(),
576 bind(&ParagraphList::push_back, ref(pl), _1));
580 void InsetText::addPreview(PreviewLoader & loader) const
582 ParagraphList::const_iterator pit = paragraphs().begin();
583 ParagraphList::const_iterator pend = paragraphs().end();
585 for (; pit != pend; ++pit) {
586 InsetList::const_iterator it = pit->insetList().begin();
587 InsetList::const_iterator end = pit->insetList().end();
588 for (; it != end; ++it)
589 it->inset->addPreview(loader);
594 ParagraphList const & InsetText::paragraphs() const
596 return text_.paragraphs();
600 ParagraphList & InsetText::paragraphs()
602 return text_.paragraphs();
606 void InsetText::updateLabels(ParIterator const & it)
608 ParIterator it2 = it;
610 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
611 if (producesOutput())
612 buffer().updateLabels(it2);
614 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
615 Counters const savecnt = tclass.counters();
616 buffer().updateLabels(it2);
617 tclass.counters() = savecnt;
622 void InsetText::tocString(odocstream & os) const
624 if (!getLayout().isInToc())
626 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
631 void InsetText::addToToc(DocIterator const & cdit)
633 DocIterator dit = cdit;
634 dit.push_back(CursorSlice(*this));
635 Toc & toc = buffer().tocBackend().toc("tableofcontents");
637 BufferParams const & bufparams = buffer_->params();
638 const int min_toclevel = bufparams.documentClass().min_toclevel();
640 // For each paragraph, traverse its insets and let them add
642 ParagraphList & pars = paragraphs();
643 pit_type pend = paragraphs().size();
644 for (pit_type pit = 0; pit != pend; ++pit) {
645 Paragraph const & par = pars[pit];
647 // the string that goes to the toc (could be the optarg)
649 InsetList::const_iterator it = par.insetList().begin();
650 InsetList::const_iterator end = par.insetList().end();
651 for (; it != end; ++it) {
652 Inset & inset = *it->inset;
654 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
656 switch (inset.lyxCode()) {
658 if (!tocstring.empty())
661 Paragraph const & insetpar =
662 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
663 if (!par.labelString().empty())
664 tocstring = par.labelString() + ' ';
665 tocstring += insetpar.asString(AS_STR_INSETS);
672 // now the toc entry for the paragraph
673 int const toclevel = par.layout().toclevel;
674 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
676 // insert this into the table of contents
677 if (tocstring.empty())
678 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
679 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
682 // And now the list of changes.
683 par.addChangesToToc(dit, buffer());
688 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
690 if (buffer().isClean())
691 return Inset::notifyCursorLeaves(old, cur);
693 // find text inset in old cursor
694 Cursor insetCur = old;
695 int scriptSlice = insetCur.find(this);
696 LASSERT(scriptSlice != -1, /**/);
697 insetCur.cutOff(scriptSlice);
698 LASSERT(&insetCur.inset() == this, /**/);
700 // update the old paragraph's words
701 insetCur.paragraph().updateWords();
703 return Inset::notifyCursorLeaves(old, cur);
707 bool InsetText::completionSupported(Cursor const & cur) const
709 //LASSERT(&cur.bv().cursor().inset() != this, return false);
710 return text_.completionSupported(cur);
714 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
716 return completionSupported(cur);
720 bool InsetText::automaticInlineCompletion() const
722 return lyxrc.completion_inline_text;
726 bool InsetText::automaticPopupCompletion() const
728 return lyxrc.completion_popup_text;
732 bool InsetText::showCompletionCursor() const
734 return lyxrc.completion_cursor_text;
738 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
740 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
744 docstring InsetText::completionPrefix(Cursor const & cur) const
746 if (!completionSupported(cur))
748 return text_.completionPrefix(cur);
752 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
755 if (!completionSupported(cur))
758 return text_.insertCompletion(cur, s, finished);
762 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
763 Dimension & dim) const
765 TextMetrics const & tm = cur.bv().textMetrics(&text_);
766 tm.completionPosAndDim(cur, x, y, dim);
770 docstring InsetText::contextMenu(BufferView const &, int, int) const
772 return from_ascii("context-edit");
776 InsetCaption const * InsetText::getCaptionInset() const
778 ParagraphList::const_iterator pit = paragraphs().begin();
779 for (; pit != paragraphs().end(); ++pit) {
780 InsetList::const_iterator it = pit->insetList().begin();
781 for (; it != pit->insetList().end(); ++it) {
782 Inset & inset = *it->inset;
783 if (inset.lyxCode() == CAPTION_CODE) {
784 InsetCaption const * ins =
785 static_cast<InsetCaption const *>(it->inset);
794 docstring InsetText::getCaptionText(OutputParams const & runparams) const
796 InsetCaption const * ins = getCaptionInset();
800 odocstringstream ods;
801 ins->getCaptionAsPlaintext(ods, runparams);
806 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
808 InsetCaption const * ins = getCaptionInset();
812 odocstringstream ods;
813 docstring def = ins->getCaptionAsHTML(ods, runparams);