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 // FIXME this use of forceLTR is dubious
278 // introduced in http://www.lyx.org/trac/changeset/21285
280 // Force any new text to latex_language FIXME: This
281 // should only be necessary in constructor, but new
282 // paragraphs that are created by pressing enter at
283 // the start of an existing paragraph get the buffer
284 // language and not latex_language, so we take this
285 // brute force approach.
286 cur.current_font.setLanguage(latex_language);
287 cur.real_current_font.setLanguage(latex_language);
290 switch (cmd.action) {
292 case LFUN_CLIPBOARD_PASTE:
293 case LFUN_SELECTION_PASTE:
294 case LFUN_PRIMARY_SELECTION_PASTE:
295 text_.dispatch(cur, cmd);
296 // If we we can only store plain text, we must reset all
298 // FIXME: Change only the pasted paragraphs
302 text_.dispatch(cur, cmd);
305 if (!cur.result().dispatched())
306 Inset::doDispatch(cur, cmd);
310 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
311 FuncStatus & status) const
313 switch (cmd.action) {
315 status.setEnabled(!forcePlainLayout());
318 case LFUN_LAYOUT_PARAGRAPH:
319 case LFUN_PARAGRAPH_PARAMS:
320 case LFUN_PARAGRAPH_PARAMS_APPLY:
321 case LFUN_PARAGRAPH_SPACING:
322 case LFUN_PARAGRAPH_UPDATE:
323 status.setEnabled(allowParagraphCustomization());
326 // Dispatch only to text_ if the cursor is inside
327 // the text_. It is not for context menus (bug 5797).
329 if (cur.text() == &text_)
330 ret = text_.getStatus(cur, cmd, status);
333 ret = Inset::getStatus(cur, cmd, status);
339 void InsetText::fixParagraphsFont()
341 Font font(inherit_font, buffer().params().language);
342 if (getLayout().isForceLtr())
343 font.setLanguage(latex_language);
344 if (getLayout().isPassThru()) {
345 ParagraphList::iterator par = paragraphs().begin();
346 ParagraphList::iterator const end = paragraphs().end();
348 par->resetFonts(font);
349 par->params().clear();
356 void InsetText::setChange(Change const & change)
358 ParagraphList::iterator pit = paragraphs().begin();
359 ParagraphList::iterator end = paragraphs().end();
360 for (; pit != end; ++pit) {
361 pit->setChange(change);
366 void InsetText::acceptChanges()
368 text_.acceptChanges(buffer().params());
372 void InsetText::rejectChanges()
374 text_.rejectChanges(buffer().params());
378 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
381 latexParagraphs(buffer(), text_, os, texrow, runparams);
382 return texrow.rows();
386 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
388 ParagraphList::const_iterator beg = paragraphs().begin();
389 ParagraphList::const_iterator end = paragraphs().end();
390 ParagraphList::const_iterator it = beg;
391 bool ref_printed = false;
393 for (; it != end; ++it) {
396 if (runparams.linelen > 0)
399 odocstringstream oss;
400 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
401 docstring const str = oss.str();
403 // FIXME: len is not computed fully correctly; in principle,
404 // we have to count the characters after the last '\n'
412 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
414 docbookParagraphs(paragraphs(), buffer(), os, runparams);
419 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
421 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
426 void InsetText::validate(LaTeXFeatures & features) const
428 for_each(paragraphs().begin(), paragraphs().end(),
429 bind(&Paragraph::validate, _1, ref(features)));
433 void InsetText::cursorPos(BufferView const & bv,
434 CursorSlice const & sl, bool boundary, int & x, int & y) const
436 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
437 y = bv.textMetrics(&text_).cursorY(sl, boundary);
441 bool InsetText::showInsetDialog(BufferView *) const
447 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
450 Paragraph & first = paragraphs().front();
451 for (unsigned int i = 0; i < data.length(); ++i)
452 first.insertChar(i, data[i], font, trackChanges);
456 void InsetText::setAutoBreakRows(bool flag)
458 if (flag == text_.autoBreakRows_)
461 text_.autoBreakRows_ = flag;
465 // remove previously existing newlines
466 ParagraphList::iterator it = paragraphs().begin();
467 ParagraphList::iterator end = paragraphs().end();
468 for (; it != end; ++it)
469 for (int i = 0; i < it->size(); ++i)
470 if (it->isNewline(i))
471 // do not track the change, because the user
472 // is not allowed to revert/reject it
473 it->eraseChar(i, false);
477 void InsetText::setDrawFrame(bool flag)
483 ColorCode InsetText::frameColor() const
489 void InsetText::setFrameColor(ColorCode col)
495 void InsetText::appendParagraphs(ParagraphList & plist)
497 // There is little we can do here to keep track of changes.
498 // As of 2006/10/20, appendParagraphs is used exclusively by
499 // LyXTabular::setMultiColumn. In this context, the paragraph break
500 // is lost irreversibly and the appended text doesn't really change
502 ParagraphList & pl = paragraphs();
504 ParagraphList::iterator pit = plist.begin();
505 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
507 mergeParagraph(buffer().params(), pl,
508 distance(pl.begin(), ins) - 1);
510 for_each(pit, plist.end(),
511 bind(&ParagraphList::push_back, ref(pl), _1));
515 void InsetText::addPreview(PreviewLoader & loader) const
517 ParagraphList::const_iterator pit = paragraphs().begin();
518 ParagraphList::const_iterator pend = paragraphs().end();
520 for (; pit != pend; ++pit) {
521 InsetList::const_iterator it = pit->insetList().begin();
522 InsetList::const_iterator end = pit->insetList().end();
523 for (; it != end; ++it)
524 it->inset->addPreview(loader);
529 ParagraphList const & InsetText::paragraphs() const
531 return text_.paragraphs();
535 ParagraphList & InsetText::paragraphs()
537 return text_.paragraphs();
541 void InsetText::updateLabels(ParIterator const & it)
543 ParIterator it2 = it;
545 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
546 if (producesOutput())
547 buffer().updateLabels(it2);
549 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
550 Counters const savecnt = tclass.counters();
551 buffer().updateLabels(it2);
552 tclass.counters() = savecnt;
557 void InsetText::addToToc(DocIterator const & cdit)
559 DocIterator dit = cdit;
560 dit.push_back(CursorSlice(*this));
561 Toc & toc = buffer().tocBackend().toc("tableofcontents");
563 BufferParams const & bufparams = buffer_->params();
564 const int min_toclevel = bufparams.documentClass().min_toclevel();
566 // For each paragraph, traverse its insets and let them add
568 ParagraphList & pars = paragraphs();
569 pit_type pend = paragraphs().size();
570 for (pit_type pit = 0; pit != pend; ++pit) {
571 Paragraph const & par = pars[pit];
573 // the string that goes to the toc (could be the optarg)
575 InsetList::const_iterator it = par.insetList().begin();
576 InsetList::const_iterator end = par.insetList().end();
577 for (; it != end; ++it) {
578 Inset & inset = *it->inset;
580 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
582 switch (inset.lyxCode()) {
584 if (!tocstring.empty())
587 Paragraph const & insetpar =
588 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
589 if (!par.labelString().empty())
590 tocstring = par.labelString() + ' ';
591 tocstring += insetpar.asString(AS_STR_INSETS);
598 // now the toc entry for the paragraph
599 int const toclevel = par.layout().toclevel;
600 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
602 // insert this into the table of contents
603 if (tocstring.empty())
604 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
605 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
608 // And now the list of changes.
609 par.addChangesToToc(dit, buffer());
614 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
616 if (buffer().isClean())
617 return Inset::notifyCursorLeaves(old, cur);
619 // find text inset in old cursor
620 Cursor insetCur = old;
621 int scriptSlice = insetCur.find(this);
622 LASSERT(scriptSlice != -1, /**/);
623 insetCur.cutOff(scriptSlice);
624 LASSERT(&insetCur.inset() == this, /**/);
626 // update the old paragraph's words
627 insetCur.paragraph().updateWords();
629 return Inset::notifyCursorLeaves(old, cur);
633 bool InsetText::completionSupported(Cursor const & cur) const
635 //LASSERT(&cur.bv().cursor().inset() != this, return false);
636 return text_.completionSupported(cur);
640 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
642 return completionSupported(cur);
646 bool InsetText::automaticInlineCompletion() const
648 return lyxrc.completion_inline_text;
652 bool InsetText::automaticPopupCompletion() const
654 return lyxrc.completion_popup_text;
658 bool InsetText::showCompletionCursor() const
660 return lyxrc.completion_cursor_text;
664 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
666 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
670 docstring InsetText::completionPrefix(Cursor const & cur) const
672 if (!completionSupported(cur))
674 return text_.completionPrefix(cur);
678 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
681 if (!completionSupported(cur))
684 return text_.insertCompletion(cur, s, finished);
688 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
689 Dimension & dim) const
691 TextMetrics const & tm = cur.bv().textMetrics(&text_);
692 tm.completionPosAndDim(cur, x, y, dim);
696 docstring InsetText::contextMenu(BufferView const &, int, int) const
698 return from_ascii("context-edit");
702 InsetCaption const * InsetText::getCaptionInset() const
704 ParagraphList::const_iterator pit = paragraphs().begin();
705 for (; pit != paragraphs().end(); ++pit) {
706 InsetList::const_iterator it = pit->insetList().begin();
707 for (; it != pit->insetList().end(); ++it) {
708 Inset & inset = *it->inset;
709 if (inset.lyxCode() == CAPTION_CODE) {
710 InsetCaption const * ins =
711 static_cast<InsetCaption const *>(it->inset);
720 docstring InsetText::getCaptionText(OutputParams const & runparams) const
722 InsetCaption const * ins = getCaptionInset();
726 odocstringstream ods;
727 ins->getCaptionAsPlaintext(ods, runparams);
732 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
734 InsetCaption const * ins = getCaptionInset();
738 odocstringstream ods;
739 docstring def = ins->getCaptionAsHTML(ods, runparams);