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"
36 #include "MetricsInfo.h"
37 #include "output_docbook.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "OutputParams.h"
41 #include "output_plaintext.h"
42 #include "paragraph_funcs.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)
80 setBuffer(const_cast<Buffer &>(buf));
85 InsetText::InsetText(InsetText const & in)
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
155 text_.write(buffer(), os);
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(buffer(), 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 docstring InsetText::editMessage() const
242 return _("Opened Text Inset");
246 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
248 pit_type const pit = front ? 0 : paragraphs().size() - 1;
249 pos_type pos = front ? 0 : paragraphs().back().size();
251 // if visual information is not to be ignored, move to extreme right/left
252 if (entry_from != ENTRY_DIRECTION_IGNORE) {
253 Cursor temp_cur = cur;
254 temp_cur.pit() = pit;
255 temp_cur.pos() = pos;
256 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
257 pos = temp_cur.pos();
260 text_.setCursor(cur.top(), pit, pos);
261 cur.clearSelection();
266 Inset * InsetText::editXY(Cursor & cur, int x, int y)
268 return cur.bv().textMetrics(&text_).editXY(cur, x, y);
272 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
274 LYXERR(Debug::ACTION, "InsetText::doDispatch()"
275 << " [ cmd.action = " << cmd.action << ']');
277 switch (cmd.action) {
279 case LFUN_CLIPBOARD_PASTE:
280 case LFUN_SELECTION_PASTE:
281 case LFUN_PRIMARY_SELECTION_PASTE:
282 text_.dispatch(cur, cmd);
283 // If we we can only store plain text, we must reset all
285 // FIXME: Change only the pasted paragraphs
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) {
302 status.setEnabled(!forcePlainLayout());
305 case LFUN_LAYOUT_PARAGRAPH:
306 case LFUN_PARAGRAPH_PARAMS:
307 case LFUN_PARAGRAPH_PARAMS_APPLY:
308 case LFUN_PARAGRAPH_SPACING:
309 case LFUN_PARAGRAPH_UPDATE:
310 status.setEnabled(allowParagraphCustomization());
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 Font font(inherit_font, buffer().params().language);
329 if (getLayout().isForceLtr())
330 font.setLanguage(latex_language);
331 if (getLayout().isPassThru()) {
332 ParagraphList::iterator par = paragraphs().begin();
333 ParagraphList::iterator const end = paragraphs().end();
335 par->resetFonts(font);
336 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(buffer().params());
359 void InsetText::rejectChanges()
361 text_.rejectChanges(buffer().params());
365 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
368 latexParagraphs(buffer(), text_, os, texrow, runparams);
369 return texrow.rows();
373 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
375 ParagraphList::const_iterator beg = paragraphs().begin();
376 ParagraphList::const_iterator end = paragraphs().end();
377 ParagraphList::const_iterator it = beg;
378 bool ref_printed = false;
380 for (; it != end; ++it) {
383 if (runparams.linelen > 0)
386 odocstringstream oss;
387 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
388 docstring const str = oss.str();
390 // FIXME: len is not computed fully correctly; in principle,
391 // we have to count the characters after the last '\n'
399 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
401 docbookParagraphs(paragraphs(), buffer(), os, runparams);
406 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
408 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
413 void InsetText::validate(LaTeXFeatures & features) const
415 for_each(paragraphs().begin(), paragraphs().end(),
416 bind(&Paragraph::validate, _1, ref(features)));
420 void InsetText::cursorPos(BufferView const & bv,
421 CursorSlice const & sl, bool boundary, int & x, int & y) const
423 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
424 y = bv.textMetrics(&text_).cursorY(sl, boundary);
428 bool InsetText::showInsetDialog(BufferView *) const
434 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
437 Paragraph & first = paragraphs().front();
438 for (unsigned int i = 0; i < data.length(); ++i)
439 first.insertChar(i, data[i], font, trackChanges);
443 void InsetText::setAutoBreakRows(bool flag)
445 if (flag == text_.autoBreakRows_)
448 text_.autoBreakRows_ = flag;
452 // remove previously existing newlines
453 ParagraphList::iterator it = paragraphs().begin();
454 ParagraphList::iterator end = paragraphs().end();
455 for (; it != end; ++it)
456 for (int i = 0; i < it->size(); ++i)
457 if (it->isNewline(i))
458 // do not track the change, because the user
459 // is not allowed to revert/reject it
460 it->eraseChar(i, false);
464 void InsetText::setDrawFrame(bool flag)
470 ColorCode InsetText::frameColor() const
476 void InsetText::setFrameColor(ColorCode col)
482 void InsetText::appendParagraphs(ParagraphList & plist)
484 // There is little we can do here to keep track of changes.
485 // As of 2006/10/20, appendParagraphs is used exclusively by
486 // LyXTabular::setMultiColumn. In this context, the paragraph break
487 // is lost irreversibly and the appended text doesn't really change
489 ParagraphList & pl = paragraphs();
491 ParagraphList::iterator pit = plist.begin();
492 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
494 mergeParagraph(buffer().params(), pl,
495 distance(pl.begin(), ins) - 1);
497 for_each(pit, plist.end(),
498 bind(&ParagraphList::push_back, ref(pl), _1));
502 void InsetText::addPreview(PreviewLoader & loader) const
504 ParagraphList::const_iterator pit = paragraphs().begin();
505 ParagraphList::const_iterator pend = paragraphs().end();
507 for (; pit != pend; ++pit) {
508 InsetList::const_iterator it = pit->insetList().begin();
509 InsetList::const_iterator end = pit->insetList().end();
510 for (; it != end; ++it)
511 it->inset->addPreview(loader);
516 ParagraphList const & InsetText::paragraphs() const
518 return text_.paragraphs();
522 ParagraphList & InsetText::paragraphs()
524 return text_.paragraphs();
528 void InsetText::updateLabels(ParIterator const & it)
530 ParIterator it2 = it;
532 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
533 if (producesOutput())
534 buffer().updateLabels(it2);
536 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
537 Counters const savecnt = tclass.counters();
538 buffer().updateLabels(it2);
539 tclass.counters() = savecnt;
544 void InsetText::addToToc(DocIterator const & cdit)
546 DocIterator dit = cdit;
547 dit.push_back(CursorSlice(*this));
548 Toc & toc = buffer().tocBackend().toc("tableofcontents");
550 BufferParams const & bufparams = buffer_->params();
551 const int min_toclevel = bufparams.documentClass().min_toclevel();
553 // For each paragraph, traverse its insets and let them add
555 ParagraphList & pars = paragraphs();
556 pit_type pend = paragraphs().size();
557 for (pit_type pit = 0; pit != pend; ++pit) {
558 Paragraph const & par = pars[pit];
560 // the string that goes to the toc (could be the optarg)
562 InsetList::const_iterator it = par.insetList().begin();
563 InsetList::const_iterator end = par.insetList().end();
564 for (; it != end; ++it) {
565 Inset & inset = *it->inset;
567 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
569 switch (inset.lyxCode()) {
571 if (!tocstring.empty())
574 Paragraph const & insetpar =
575 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
576 if (!par.labelString().empty())
577 tocstring = par.labelString() + ' ';
578 tocstring += insetpar.asString(AS_STR_INSETS);
585 // now the toc entry for the paragraph
586 int const toclevel = par.layout().toclevel;
587 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
589 // insert this into the table of contents
590 if (tocstring.empty())
591 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
592 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
595 // And now the list of changes.
596 par.addChangesToToc(dit, buffer());
601 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
603 if (buffer().isClean())
604 return Inset::notifyCursorLeaves(old, cur);
606 // find text inset in old cursor
607 Cursor insetCur = old;
608 int scriptSlice = insetCur.find(this);
609 LASSERT(scriptSlice != -1, /**/);
610 insetCur.cutOff(scriptSlice);
611 LASSERT(&insetCur.inset() == this, /**/);
613 // update the old paragraph's words
614 insetCur.paragraph().updateWords();
616 return Inset::notifyCursorLeaves(old, cur);
620 bool InsetText::completionSupported(Cursor const & cur) const
622 //LASSERT(&cur.bv().cursor().inset() != this, return false);
623 return text_.completionSupported(cur);
627 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
629 return completionSupported(cur);
633 bool InsetText::automaticInlineCompletion() const
635 return lyxrc.completion_inline_text;
639 bool InsetText::automaticPopupCompletion() const
641 return lyxrc.completion_popup_text;
645 bool InsetText::showCompletionCursor() const
647 return lyxrc.completion_cursor_text;
651 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
653 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
657 docstring InsetText::completionPrefix(Cursor const & cur) const
659 if (!completionSupported(cur))
661 return text_.completionPrefix(cur);
665 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
668 if (!completionSupported(cur))
671 return text_.insertCompletion(cur, s, finished);
675 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
676 Dimension & dim) const
678 TextMetrics const & tm = cur.bv().textMetrics(&text_);
679 tm.completionPosAndDim(cur, x, y, dim);
683 docstring InsetText::contextMenu(BufferView const &, int, int) const
685 return from_ascii("context-edit");
689 InsetCaption const * InsetText::getCaptionInset() const
691 ParagraphList::const_iterator pit = paragraphs().begin();
692 for (; pit != paragraphs().end(); ++pit) {
693 InsetList::const_iterator it = pit->insetList().begin();
694 for (; it != pit->insetList().end(); ++it) {
695 Inset & inset = *it->inset;
696 if (inset.lyxCode() == CAPTION_CODE) {
697 InsetCaption const * ins =
698 static_cast<InsetCaption const *>(it->inset);
707 docstring InsetText::getCaptionText(OutputParams const & runparams) const
709 InsetCaption const * ins = getCaptionInset();
713 odocstringstream ods;
714 ins->getCaptionAsPlaintext(ods, runparams);
719 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
721 InsetCaption const * ins = getCaptionInset();
725 odocstringstream ods;
726 docstring def = ins->getCaptionAsHTML(ods, runparams);