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 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
243 pit_type const pit = front ? 0 : paragraphs().size() - 1;
244 pos_type pos = front ? 0 : paragraphs().back().size();
246 // if visual information is not to be ignored, move to extreme right/left
247 if (entry_from != ENTRY_DIRECTION_IGNORE) {
248 Cursor temp_cur = cur;
249 temp_cur.pit() = pit;
250 temp_cur.pos() = pos;
251 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
252 pos = temp_cur.pos();
255 text_.setCursor(cur.top(), pit, pos);
256 cur.clearSelection();
261 Inset * InsetText::editXY(Cursor & cur, int x, int y)
263 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
267 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
269 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
270 << " [ cmd.action = " << cmd.action << ']');
272 // FIXME this use of forceLTR is dubious
273 // introduced in http://www.lyx.org/trac/changeset/21285
275 // Force any new text to latex_language FIXME: This
276 // should only be necessary in constructor, but new
277 // paragraphs that are created by pressing enter at
278 // the start of an existing paragraph get the buffer
279 // language and not latex_language, so we take this
280 // brute force approach.
281 cur.current_font.setLanguage(latex_language);
282 cur.real_current_font.setLanguage(latex_language);
285 switch (cmd.action) {
287 case LFUN_CLIPBOARD_PASTE:
288 case LFUN_SELECTION_PASTE:
289 case LFUN_PRIMARY_SELECTION_PASTE:
290 text_.dispatch(cur, cmd);
291 // If we we can only store plain text, we must reset all
293 // FIXME: Change only the pasted paragraphs
297 text_.dispatch(cur, cmd);
300 if (!cur.result().dispatched())
301 Inset::doDispatch(cur, cmd);
305 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
306 FuncStatus & status) const
308 switch (cmd.action) {
310 status.setEnabled(!forcePlainLayout());
313 case LFUN_LAYOUT_PARAGRAPH:
314 case LFUN_PARAGRAPH_PARAMS:
315 case LFUN_PARAGRAPH_PARAMS_APPLY:
316 case LFUN_PARAGRAPH_SPACING:
317 case LFUN_PARAGRAPH_UPDATE:
318 status.setEnabled(allowParagraphCustomization());
321 // Dispatch only to text_ if the cursor is inside
322 // the text_. It is not for context menus (bug 5797).
324 if (cur.text() == &text_)
325 ret = text_.getStatus(cur, cmd, status);
328 ret = Inset::getStatus(cur, cmd, status);
334 void InsetText::fixParagraphsFont()
336 Font font(inherit_font, buffer().params().language);
337 if (getLayout().isForceLtr())
338 font.setLanguage(latex_language);
339 if (getLayout().isPassThru()) {
340 ParagraphList::iterator par = paragraphs().begin();
341 ParagraphList::iterator const end = paragraphs().end();
343 par->resetFonts(font);
344 par->params().clear();
351 void InsetText::setChange(Change const & change)
353 ParagraphList::iterator pit = paragraphs().begin();
354 ParagraphList::iterator end = paragraphs().end();
355 for (; pit != end; ++pit) {
356 pit->setChange(change);
361 void InsetText::acceptChanges()
363 text_.acceptChanges(buffer().params());
367 void InsetText::rejectChanges()
369 text_.rejectChanges(buffer().params());
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 docbookParagraphs(paragraphs(), buffer(), os, runparams);
453 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
455 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
460 void InsetText::validate(LaTeXFeatures & features) const
462 features.useInsetLayout(getLayout());
463 for_each(paragraphs().begin(), paragraphs().end(),
464 bind(&Paragraph::validate, _1, ref(features)));
468 void InsetText::cursorPos(BufferView const & bv,
469 CursorSlice const & sl, bool boundary, int & x, int & y) const
471 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
472 y = bv.textMetrics(&text_).cursorY(sl, boundary);
476 bool InsetText::showInsetDialog(BufferView *) const
482 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
485 Paragraph & first = paragraphs().front();
486 for (unsigned int i = 0; i < data.length(); ++i)
487 first.insertChar(i, data[i], font, trackChanges);
491 void InsetText::setAutoBreakRows(bool flag)
493 if (flag == text_.autoBreakRows_)
496 text_.autoBreakRows_ = flag;
500 // remove previously existing newlines
501 ParagraphList::iterator it = paragraphs().begin();
502 ParagraphList::iterator end = paragraphs().end();
503 for (; it != end; ++it)
504 for (int i = 0; i < it->size(); ++i)
505 if (it->isNewline(i))
506 // do not track the change, because the user
507 // is not allowed to revert/reject it
508 it->eraseChar(i, false);
512 void InsetText::setDrawFrame(bool flag)
518 ColorCode InsetText::frameColor() const
524 void InsetText::setFrameColor(ColorCode col)
530 void InsetText::appendParagraphs(ParagraphList & plist)
532 // There is little we can do here to keep track of changes.
533 // As of 2006/10/20, appendParagraphs is used exclusively by
534 // LyXTabular::setMultiColumn. In this context, the paragraph break
535 // is lost irreversibly and the appended text doesn't really change
537 ParagraphList & pl = paragraphs();
539 ParagraphList::iterator pit = plist.begin();
540 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
542 mergeParagraph(buffer().params(), pl,
543 distance(pl.begin(), ins) - 1);
545 for_each(pit, plist.end(),
546 bind(&ParagraphList::push_back, ref(pl), _1));
550 void InsetText::addPreview(PreviewLoader & loader) const
552 ParagraphList::const_iterator pit = paragraphs().begin();
553 ParagraphList::const_iterator pend = paragraphs().end();
555 for (; pit != pend; ++pit) {
556 InsetList::const_iterator it = pit->insetList().begin();
557 InsetList::const_iterator end = pit->insetList().end();
558 for (; it != end; ++it)
559 it->inset->addPreview(loader);
564 ParagraphList const & InsetText::paragraphs() const
566 return text_.paragraphs();
570 ParagraphList & InsetText::paragraphs()
572 return text_.paragraphs();
576 void InsetText::updateLabels(ParIterator const & it)
578 ParIterator it2 = it;
580 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
581 if (producesOutput())
582 buffer().updateLabels(it2);
584 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
585 Counters const savecnt = tclass.counters();
586 buffer().updateLabels(it2);
587 tclass.counters() = savecnt;
592 void InsetText::addToToc(DocIterator const & cdit)
594 DocIterator dit = cdit;
595 dit.push_back(CursorSlice(*this));
596 Toc & toc = buffer().tocBackend().toc("tableofcontents");
598 BufferParams const & bufparams = buffer_->params();
599 const int min_toclevel = bufparams.documentClass().min_toclevel();
601 // For each paragraph, traverse its insets and let them add
603 ParagraphList & pars = paragraphs();
604 pit_type pend = paragraphs().size();
605 for (pit_type pit = 0; pit != pend; ++pit) {
606 Paragraph const & par = pars[pit];
608 // the string that goes to the toc (could be the optarg)
610 InsetList::const_iterator it = par.insetList().begin();
611 InsetList::const_iterator end = par.insetList().end();
612 for (; it != end; ++it) {
613 Inset & inset = *it->inset;
615 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
617 switch (inset.lyxCode()) {
619 if (!tocstring.empty())
622 Paragraph const & insetpar =
623 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
624 if (!par.labelString().empty())
625 tocstring = par.labelString() + ' ';
626 tocstring += insetpar.asString(AS_STR_INSETS);
633 // now the toc entry for the paragraph
634 int const toclevel = par.layout().toclevel;
635 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
637 // insert this into the table of contents
638 if (tocstring.empty())
639 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
640 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
643 // And now the list of changes.
644 par.addChangesToToc(dit, buffer());
649 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
651 if (buffer().isClean())
652 return Inset::notifyCursorLeaves(old, cur);
654 // find text inset in old cursor
655 Cursor insetCur = old;
656 int scriptSlice = insetCur.find(this);
657 LASSERT(scriptSlice != -1, /**/);
658 insetCur.cutOff(scriptSlice);
659 LASSERT(&insetCur.inset() == this, /**/);
661 // update the old paragraph's words
662 insetCur.paragraph().updateWords();
664 return Inset::notifyCursorLeaves(old, cur);
668 bool InsetText::completionSupported(Cursor const & cur) const
670 //LASSERT(&cur.bv().cursor().inset() != this, return false);
671 return text_.completionSupported(cur);
675 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
677 return completionSupported(cur);
681 bool InsetText::automaticInlineCompletion() const
683 return lyxrc.completion_inline_text;
687 bool InsetText::automaticPopupCompletion() const
689 return lyxrc.completion_popup_text;
693 bool InsetText::showCompletionCursor() const
695 return lyxrc.completion_cursor_text;
699 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
701 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
705 docstring InsetText::completionPrefix(Cursor const & cur) const
707 if (!completionSupported(cur))
709 return text_.completionPrefix(cur);
713 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
716 if (!completionSupported(cur))
719 return text_.insertCompletion(cur, s, finished);
723 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
724 Dimension & dim) const
726 TextMetrics const & tm = cur.bv().textMetrics(&text_);
727 tm.completionPosAndDim(cur, x, y, dim);
731 docstring InsetText::contextMenu(BufferView const &, int, int) const
733 return from_ascii("context-edit");
737 InsetCaption const * InsetText::getCaptionInset() const
739 ParagraphList::const_iterator pit = paragraphs().begin();
740 for (; pit != paragraphs().end(); ++pit) {
741 InsetList::const_iterator it = pit->insetList().begin();
742 for (; it != pit->insetList().end(); ++it) {
743 Inset & inset = *it->inset;
744 if (inset.lyxCode() == CAPTION_CODE) {
745 InsetCaption const * ins =
746 static_cast<InsetCaption const *>(it->inset);
755 docstring InsetText::getCaptionText(OutputParams const & runparams) const
757 InsetCaption const * ins = getCaptionInset();
761 odocstringstream ods;
762 ins->getCaptionAsPlaintext(ods, runparams);
767 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
769 InsetCaption const * ins = getCaptionInset();
773 odocstringstream ods;
774 docstring def = ins->getCaptionAsHTML(ods, runparams);