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_funcs.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
50 #include "TextClass.h"
52 #include "TextMetrics.h"
53 #include "TocBackend.h"
55 #include "frontends/alert.h"
56 #include "frontends/Painter.h"
58 #include "support/debug.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
62 #include <boost/bind.hpp>
63 #include "support/lassert.h"
66 using namespace lyx::support;
73 using graphics::PreviewLoader;
76 /////////////////////////////////////////////////////////////////////
78 InsetText::InsetText(Buffer const & buf, UsePlain type)
79 : drawFrame_(false), frame_color_(Color_insetframe)
81 setBuffer(const_cast<Buffer &>(buf));
86 InsetText::InsetText(InsetText const & in)
89 text_.autoBreakRows_ = in.text_.autoBreakRows_;
90 drawFrame_ = in.drawFrame_;
91 frame_color_ = in.frame_color_;
92 text_.paragraphs() = in.text_.paragraphs();
97 void InsetText::setBuffer(Buffer & buf)
99 ParagraphList::iterator end = paragraphs().end();
100 for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
102 Inset::setBuffer(buf);
106 void InsetText::initParagraphs(UsePlain type)
108 LASSERT(paragraphs().empty(), /**/);
109 paragraphs().push_back(Paragraph());
110 Paragraph & ourpar = paragraphs().back();
111 ourpar.setInsetOwner(this);
112 DocumentClass const & dc = buffer_->params().documentClass();
113 if (type == DefaultLayout)
114 ourpar.setDefaultLayout(dc);
116 ourpar.setPlainLayout(dc);
120 void InsetText::setParagraphOwner()
122 for_each(paragraphs().begin(), paragraphs().end(),
123 bind(&Paragraph::setInsetOwner, _1, this));
127 void InsetText::clear()
129 ParagraphList & pars = paragraphs();
130 LASSERT(!pars.empty(), /**/);
132 // This is a gross hack...
133 Layout const & old_layout = pars.begin()->layout();
136 pars.push_back(Paragraph());
137 pars.begin()->setInsetOwner(this);
138 pars.begin()->setLayout(old_layout);
142 Dimension const InsetText::dimension(BufferView const & bv) const
144 TextMetrics const & tm = bv.textMetrics(&text_);
145 Dimension dim = tm.dimension();
146 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
147 dim.des += TEXT_TO_INSET_OFFSET;
148 dim.asc += TEXT_TO_INSET_OFFSET;
153 void InsetText::write(ostream & os) const
156 text_.write(buffer(), os);
160 void InsetText::read(Lexer & lex)
164 // delete the initial paragraph
165 Paragraph oldpar = *paragraphs().begin();
166 paragraphs().clear();
168 lex.setContext("InsetText::read");
169 bool res = text_.read(buffer(), lex, errorList, this);
172 lex.printError("Missing \\end_inset at this point. ");
175 // ensure we have at least one paragraph.
176 if (paragraphs().empty())
177 paragraphs().push_back(oldpar);
178 // Force default font, if so requested
179 // This avoids paragraphs in buffer language that would have a
180 // foreign language after a document language change, and it ensures
181 // that all new text in ERT and similar gets the "latex" language,
182 // since new text inherits the language from the last position of the
183 // existing text. As a side effect this makes us also robust against
184 // bugs in LyX that might lead to font changes in ERT in .lyx files.
189 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
191 TextMetrics & tm = mi.base.bv->textMetrics(&text_);
193 //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
195 // Hand font through to contained lyxtext:
196 tm.font_.fontInfo() = mi.base.font;
197 mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
199 // This can happen when a layout has a left and right margin,
200 // and the view is made very narrow. We can't do better than
201 // to draw it partly out of view (bug 5890).
202 if (mi.base.textwidth < 1)
203 mi.base.textwidth = 1;
206 tm.metrics(mi, dim, mi.base.textwidth);
209 mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
210 dim.asc += TEXT_TO_INSET_OFFSET;
211 dim.des += TEXT_TO_INSET_OFFSET;
212 dim.wid += 2 * TEXT_TO_INSET_OFFSET;
216 void InsetText::draw(PainterInfo & pi, int x, int y) const
218 TextMetrics & tm = pi.base.bv->textMetrics(&text_);
220 if (drawFrame_ || pi.full_repaint) {
221 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
222 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
223 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
224 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
226 pi.pain.fillRectangle(xframe, yframe, w, h,
227 pi.backgroundColor(this));
230 pi.pain.rectangle(xframe, yframe, w, h, frameColor());
232 ColorCode const old_color = pi.background_color;
233 pi.background_color = pi.backgroundColor(this, false);
235 tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
237 pi.background_color = old_color;
241 docstring InsetText::editMessage() const
243 return _("Opened Text Inset");
247 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
249 pit_type const pit = front ? 0 : paragraphs().size() - 1;
250 pos_type pos = front ? 0 : paragraphs().back().size();
252 // if visual information is not to be ignored, move to extreme right/left
253 if (entry_from != ENTRY_DIRECTION_IGNORE) {
254 Cursor temp_cur = cur;
255 temp_cur.pit() = pit;
256 temp_cur.pos() = pos;
257 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
258 pos = temp_cur.pos();
261 text_.setCursor(cur.top(), pit, pos);
262 cur.clearSelection();
267 Inset * InsetText::editXY(Cursor & cur, int x, int y)
269 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
273 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
275 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
276 << " [ cmd.action = " << cmd.action << ']');
278 // FIXME this use of forceLTR is dubious
279 // introduced in http://www.lyx.org/trac/changeset/21285
281 // Force any new text to latex_language FIXME: This
282 // should only be necessary in constructor, but new
283 // paragraphs that are created by pressing enter at
284 // the start of an existing paragraph get the buffer
285 // language and not latex_language, so we take this
286 // brute force approach.
287 cur.current_font.setLanguage(latex_language);
288 cur.real_current_font.setLanguage(latex_language);
291 switch (cmd.action) {
293 case LFUN_CLIPBOARD_PASTE:
294 case LFUN_SELECTION_PASTE:
295 case LFUN_PRIMARY_SELECTION_PASTE:
296 text_.dispatch(cur, cmd);
297 // If we we can only store plain text, we must reset all
299 // FIXME: Change only the pasted paragraphs
303 text_.dispatch(cur, cmd);
306 if (!cur.result().dispatched())
307 Inset::doDispatch(cur, cmd);
311 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
312 FuncStatus & status) const
314 switch (cmd.action) {
316 status.setEnabled(!forcePlainLayout());
319 case LFUN_LAYOUT_PARAGRAPH:
320 case LFUN_PARAGRAPH_PARAMS:
321 case LFUN_PARAGRAPH_PARAMS_APPLY:
322 case LFUN_PARAGRAPH_SPACING:
323 case LFUN_PARAGRAPH_UPDATE:
324 status.setEnabled(allowParagraphCustomization());
327 // Dispatch only to text_ if the cursor is inside
328 // the text_. It is not for context menus (bug 5797).
330 if (cur.text() == &text_)
331 ret = text_.getStatus(cur, cmd, status);
334 ret = Inset::getStatus(cur, cmd, status);
340 void InsetText::fixParagraphsFont()
342 Font font(inherit_font, buffer().params().language);
343 if (getLayout().isForceLtr())
344 font.setLanguage(latex_language);
345 if (getLayout().isPassThru()) {
346 ParagraphList::iterator par = paragraphs().begin();
347 ParagraphList::iterator const end = paragraphs().end();
349 par->resetFonts(font);
350 par->params().clear();
357 void InsetText::setChange(Change const & change)
359 ParagraphList::iterator pit = paragraphs().begin();
360 ParagraphList::iterator end = paragraphs().end();
361 for (; pit != end; ++pit) {
362 pit->setChange(change);
367 void InsetText::acceptChanges()
369 text_.acceptChanges(buffer().params());
373 void InsetText::rejectChanges()
375 text_.rejectChanges(buffer().params());
379 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
381 // This implements the standard way of handling the LaTeX
382 // output of a text inset, either a command or an
383 // environment. Standard collapsable insets should not
384 // redefine this, non-standard ones may call this.
385 InsetLayout const & il = getLayout();
387 if (!il.latexname().empty()) {
388 if (il.latextype() == InsetLayout::COMMAND) {
390 if (runparams.moving_arg)
392 os << '\\' << from_utf8(il.latexname());
393 if (!il.latexparam().empty())
394 os << from_utf8(il.latexparam());
396 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
397 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
398 if (!il.latexparam().empty())
399 os << from_utf8(il.latexparam());
403 OutputParams rp = runparams;
406 if (il.isNeedProtect())
407 rp.moving_arg = true;
409 // Output the contents of the inset
411 latexParagraphs(buffer(), text_, os, texrow, rp);
412 rows += texrow.rows();
414 if (!il.latexname().empty()) {
415 if (il.latextype() == InsetLayout::COMMAND) {
417 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
418 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
426 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
428 ParagraphList::const_iterator beg = paragraphs().begin();
429 ParagraphList::const_iterator end = paragraphs().end();
430 ParagraphList::const_iterator it = beg;
431 bool ref_printed = false;
433 for (; it != end; ++it) {
436 if (runparams.linelen > 0)
439 odocstringstream oss;
440 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
441 docstring const str = oss.str();
443 // FIXME: len is not computed fully correctly; in principle,
444 // we have to count the characters after the last '\n'
452 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
454 docbookParagraphs(paragraphs(), buffer(), os, runparams);
459 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
461 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
466 void InsetText::validate(LaTeXFeatures & features) const
468 features.useInsetLayout(getLayout());
469 for_each(paragraphs().begin(), paragraphs().end(),
470 bind(&Paragraph::validate, _1, ref(features)));
474 void InsetText::cursorPos(BufferView const & bv,
475 CursorSlice const & sl, bool boundary, int & x, int & y) const
477 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
478 y = bv.textMetrics(&text_).cursorY(sl, boundary);
482 bool InsetText::showInsetDialog(BufferView *) const
488 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
491 Paragraph & first = paragraphs().front();
492 for (unsigned int i = 0; i < data.length(); ++i)
493 first.insertChar(i, data[i], font, trackChanges);
497 void InsetText::setAutoBreakRows(bool flag)
499 if (flag == text_.autoBreakRows_)
502 text_.autoBreakRows_ = flag;
506 // remove previously existing newlines
507 ParagraphList::iterator it = paragraphs().begin();
508 ParagraphList::iterator end = paragraphs().end();
509 for (; it != end; ++it)
510 for (int i = 0; i < it->size(); ++i)
511 if (it->isNewline(i))
512 // do not track the change, because the user
513 // is not allowed to revert/reject it
514 it->eraseChar(i, false);
518 void InsetText::setDrawFrame(bool flag)
524 ColorCode InsetText::frameColor() const
530 void InsetText::setFrameColor(ColorCode col)
536 void InsetText::appendParagraphs(ParagraphList & plist)
538 // There is little we can do here to keep track of changes.
539 // As of 2006/10/20, appendParagraphs is used exclusively by
540 // LyXTabular::setMultiColumn. In this context, the paragraph break
541 // is lost irreversibly and the appended text doesn't really change
543 ParagraphList & pl = paragraphs();
545 ParagraphList::iterator pit = plist.begin();
546 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
548 mergeParagraph(buffer().params(), pl,
549 distance(pl.begin(), ins) - 1);
551 for_each(pit, plist.end(),
552 bind(&ParagraphList::push_back, ref(pl), _1));
556 void InsetText::addPreview(PreviewLoader & loader) const
558 ParagraphList::const_iterator pit = paragraphs().begin();
559 ParagraphList::const_iterator pend = paragraphs().end();
561 for (; pit != pend; ++pit) {
562 InsetList::const_iterator it = pit->insetList().begin();
563 InsetList::const_iterator end = pit->insetList().end();
564 for (; it != end; ++it)
565 it->inset->addPreview(loader);
570 ParagraphList const & InsetText::paragraphs() const
572 return text_.paragraphs();
576 ParagraphList & InsetText::paragraphs()
578 return text_.paragraphs();
582 void InsetText::updateLabels(ParIterator const & it)
584 ParIterator it2 = it;
586 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
587 if (producesOutput())
588 buffer().updateLabels(it2);
590 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
591 Counters const savecnt = tclass.counters();
592 buffer().updateLabels(it2);
593 tclass.counters() = savecnt;
598 void InsetText::addToToc(DocIterator const & cdit)
600 DocIterator dit = cdit;
601 dit.push_back(CursorSlice(*this));
602 Toc & toc = buffer().tocBackend().toc("tableofcontents");
604 BufferParams const & bufparams = buffer_->params();
605 const int min_toclevel = bufparams.documentClass().min_toclevel();
607 // For each paragraph, traverse its insets and let them add
609 ParagraphList & pars = paragraphs();
610 pit_type pend = paragraphs().size();
611 for (pit_type pit = 0; pit != pend; ++pit) {
612 Paragraph const & par = pars[pit];
614 // the string that goes to the toc (could be the optarg)
616 InsetList::const_iterator it = par.insetList().begin();
617 InsetList::const_iterator end = par.insetList().end();
618 for (; it != end; ++it) {
619 Inset & inset = *it->inset;
621 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
623 switch (inset.lyxCode()) {
625 if (!tocstring.empty())
628 Paragraph const & insetpar =
629 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
630 if (!par.labelString().empty())
631 tocstring = par.labelString() + ' ';
632 tocstring += insetpar.asString(AS_STR_INSETS);
639 // now the toc entry for the paragraph
640 int const toclevel = par.layout().toclevel;
641 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
643 // insert this into the table of contents
644 if (tocstring.empty())
645 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
646 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
649 // And now the list of changes.
650 par.addChangesToToc(dit, buffer());
655 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
657 if (buffer().isClean())
658 return Inset::notifyCursorLeaves(old, cur);
660 // find text inset in old cursor
661 Cursor insetCur = old;
662 int scriptSlice = insetCur.find(this);
663 LASSERT(scriptSlice != -1, /**/);
664 insetCur.cutOff(scriptSlice);
665 LASSERT(&insetCur.inset() == this, /**/);
667 // update the old paragraph's words
668 insetCur.paragraph().updateWords();
670 return Inset::notifyCursorLeaves(old, cur);
674 bool InsetText::completionSupported(Cursor const & cur) const
676 //LASSERT(&cur.bv().cursor().inset() != this, return false);
677 return text_.completionSupported(cur);
681 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
683 return completionSupported(cur);
687 bool InsetText::automaticInlineCompletion() const
689 return lyxrc.completion_inline_text;
693 bool InsetText::automaticPopupCompletion() const
695 return lyxrc.completion_popup_text;
699 bool InsetText::showCompletionCursor() const
701 return lyxrc.completion_cursor_text;
705 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
707 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
711 docstring InsetText::completionPrefix(Cursor const & cur) const
713 if (!completionSupported(cur))
715 return text_.completionPrefix(cur);
719 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
722 if (!completionSupported(cur))
725 return text_.insertCompletion(cur, s, finished);
729 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
730 Dimension & dim) const
732 TextMetrics const & tm = cur.bv().textMetrics(&text_);
733 tm.completionPosAndDim(cur, x, y, dim);
737 docstring InsetText::contextMenu(BufferView const &, int, int) const
739 return from_ascii("context-edit");
743 InsetCaption const * InsetText::getCaptionInset() const
745 ParagraphList::const_iterator pit = paragraphs().begin();
746 for (; pit != paragraphs().end(); ++pit) {
747 InsetList::const_iterator it = pit->insetList().begin();
748 for (; it != pit->insetList().end(); ++it) {
749 Inset & inset = *it->inset;
750 if (inset.lyxCode() == CAPTION_CODE) {
751 InsetCaption const * ins =
752 static_cast<InsetCaption const *>(it->inset);
761 docstring InsetText::getCaptionText(OutputParams const & runparams) const
763 InsetCaption const * ins = getCaptionInset();
767 odocstringstream ods;
768 ins->getCaptionAsPlaintext(ods, runparams);
773 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
775 InsetCaption const * ins = getCaptionInset();
779 odocstringstream ods;
780 docstring def = ins->getCaptionAsHTML(ods, runparams);