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 if (getLayout().isPassThru()) {
273 // Force any new text to latex_language FIXME: This
274 // should only be necessary in constructor, but new
275 // paragraphs that are created by pressing enter at
276 // the start of an existing paragraph get the buffer
277 // language and not latex_language, so we take this
278 // brute force approach.
279 cur.current_font.setLanguage(latex_language);
280 cur.real_current_font.setLanguage(latex_language);
283 switch (cmd.action) {
285 case LFUN_CLIPBOARD_PASTE:
286 case LFUN_SELECTION_PASTE:
287 case LFUN_PRIMARY_SELECTION_PASTE:
288 text_.dispatch(cur, cmd);
289 // If we we can only store plain text, we must reset all
291 // FIXME: Change only the pasted paragraphs
295 text_.dispatch(cur, cmd);
298 if (!cur.result().dispatched())
299 Inset::doDispatch(cur, cmd);
303 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
304 FuncStatus & status) const
306 switch (cmd.action) {
308 status.setEnabled(!forcePlainLayout());
311 case LFUN_LAYOUT_PARAGRAPH:
312 case LFUN_PARAGRAPH_PARAMS:
313 case LFUN_PARAGRAPH_PARAMS_APPLY:
314 case LFUN_PARAGRAPH_UPDATE:
315 status.setEnabled(allowParagraphCustomization());
318 // Dispatch only to text_ if the cursor is inside
319 // the text_. It is not for context menus (bug 5797).
321 if (cur.text() == &text_)
322 ret = text_.getStatus(cur, cmd, status);
325 ret = Inset::getStatus(cur, cmd, status);
331 void InsetText::fixParagraphsFont()
333 if (!getLayout().isPassThru())
336 Font font(inherit_font, buffer().params().language);
337 font.setLanguage(latex_language);
338 ParagraphList::iterator par = paragraphs().begin();
339 ParagraphList::iterator const end = paragraphs().end();
341 par->resetFonts(font);
342 par->params().clear();
348 void InsetText::setChange(Change const & change)
350 ParagraphList::iterator pit = paragraphs().begin();
351 ParagraphList::iterator end = paragraphs().end();
352 for (; pit != end; ++pit) {
353 pit->setChange(change);
358 void InsetText::acceptChanges()
360 text_.acceptChanges(buffer().params());
364 void InsetText::rejectChanges()
366 text_.rejectChanges(buffer().params());
370 void InsetText::validate(LaTeXFeatures & features) const
372 features.useInsetLayout(getLayout());
373 for_each(paragraphs().begin(), paragraphs().end(),
374 bind(&Paragraph::validate, _1, ref(features)));
378 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
380 // This implements the standard way of handling the LaTeX
381 // output of a text inset, either a command or an
382 // environment. Standard collapsable insets should not
383 // redefine this, non-standard ones may call this.
384 InsetLayout const & il = getLayout();
386 if (!il.latexname().empty()) {
387 if (il.latextype() == InsetLayout::COMMAND) {
389 if (runparams.moving_arg)
391 os << '\\' << from_utf8(il.latexname());
392 if (!il.latexparam().empty())
393 os << from_utf8(il.latexparam());
395 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
396 os << "%\n\\begin{" << from_utf8(il.latexname()) << "}\n";
397 if (!il.latexparam().empty())
398 os << from_utf8(il.latexparam());
402 OutputParams rp = runparams;
405 if (il.isNeedProtect())
406 rp.moving_arg = true;
408 // Output the contents of the inset
410 latexParagraphs(buffer(), text_, os, texrow, rp);
411 rows += texrow.rows();
413 if (!il.latexname().empty()) {
414 if (il.latextype() == InsetLayout::COMMAND) {
416 } else if (il.latextype() == InsetLayout::ENVIRONMENT) {
417 os << "\n\\end{" << from_utf8(il.latexname()) << "}\n";
425 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
427 ParagraphList::const_iterator beg = paragraphs().begin();
428 ParagraphList::const_iterator end = paragraphs().end();
429 ParagraphList::const_iterator it = beg;
430 bool ref_printed = false;
432 for (; it != end; ++it) {
435 if (runparams.linelen > 0)
438 odocstringstream oss;
439 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
440 docstring const str = oss.str();
442 // FIXME: len is not computed fully correctly; in principle,
443 // we have to count the characters after the last '\n'
451 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
453 ParagraphList::const_iterator const beg = paragraphs().begin();
456 sgml::openTag(os, getLayout().latexname(),
457 beg->getID(buffer(), runparams) + getLayout().latexparam());
459 docbookParagraphs(paragraphs(), buffer(), os, runparams);
462 sgml::closeTag(os, getLayout().latexname());
468 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
470 InsetLayout const & il = getLayout();
472 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
476 bool const opened = html::openTag(os, il.htmltag(), il.htmlattr());
477 if (!il.counter().empty()) {
478 BufferParams const & bp = buffer().masterBuffer()->params();
479 Counters & cntrs = bp.documentClass().counters();
480 cntrs.step(il.counter());
481 // FIXME: translate to paragraph language
482 if (!il.htmllabel().empty())
483 os << cntrs.counterLabel(from_utf8(il.htmllabel()), bp.language->code());
485 bool innertag_opened = false;
486 if (!il.htmlinnertag().empty())
487 innertag_opened = html::openTag(os, il.htmlinnertag(), il.htmlinnerattr());
489 xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
492 html::closeTag(os, il.htmlinnertag());
494 html::closeTag(os, il.htmltag());
499 void InsetText::cursorPos(BufferView const & bv,
500 CursorSlice const & sl, bool boundary, int & x, int & y) const
502 x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
503 y = bv.textMetrics(&text_).cursorY(sl, boundary);
507 bool InsetText::showInsetDialog(BufferView *) const
513 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
516 Paragraph & first = paragraphs().front();
517 for (unsigned int i = 0; i < data.length(); ++i)
518 first.insertChar(i, data[i], font, trackChanges);
522 void InsetText::setAutoBreakRows(bool flag)
524 if (flag == text_.autoBreakRows_)
527 text_.autoBreakRows_ = flag;
531 // remove previously existing newlines
532 ParagraphList::iterator it = paragraphs().begin();
533 ParagraphList::iterator end = paragraphs().end();
534 for (; it != end; ++it)
535 for (int i = 0; i < it->size(); ++i)
536 if (it->isNewline(i))
537 // do not track the change, because the user
538 // is not allowed to revert/reject it
539 it->eraseChar(i, false);
543 void InsetText::setDrawFrame(bool flag)
549 ColorCode InsetText::frameColor() const
555 void InsetText::setFrameColor(ColorCode col)
561 void InsetText::appendParagraphs(ParagraphList & plist)
563 // There is little we can do here to keep track of changes.
564 // As of 2006/10/20, appendParagraphs is used exclusively by
565 // LyXTabular::setMultiColumn. In this context, the paragraph break
566 // is lost irreversibly and the appended text doesn't really change
568 ParagraphList & pl = paragraphs();
570 ParagraphList::iterator pit = plist.begin();
571 ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
573 mergeParagraph(buffer().params(), pl,
574 distance(pl.begin(), ins) - 1);
576 for_each(pit, plist.end(),
577 bind(&ParagraphList::push_back, ref(pl), _1));
581 void InsetText::addPreview(PreviewLoader & loader) const
583 ParagraphList::const_iterator pit = paragraphs().begin();
584 ParagraphList::const_iterator pend = paragraphs().end();
586 for (; pit != pend; ++pit) {
587 InsetList::const_iterator it = pit->insetList().begin();
588 InsetList::const_iterator end = pit->insetList().end();
589 for (; it != end; ++it)
590 it->inset->addPreview(loader);
595 ParagraphList const & InsetText::paragraphs() const
597 return text_.paragraphs();
601 ParagraphList & InsetText::paragraphs()
603 return text_.paragraphs();
607 void InsetText::updateLabels(ParIterator const & it)
609 ParIterator it2 = it;
611 LASSERT(&it2.inset() == this && it2.pit() == 0, return);
612 if (producesOutput())
613 buffer().updateLabels(it2);
615 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
616 Counters const savecnt = tclass.counters();
617 buffer().updateLabels(it2);
618 tclass.counters() = savecnt;
623 void InsetText::tocString(odocstream & os) const
625 if (!getLayout().isInToc())
627 os << text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
632 void InsetText::addToToc(DocIterator const & cdit)
634 DocIterator dit = cdit;
635 dit.push_back(CursorSlice(*this));
636 Toc & toc = buffer().tocBackend().toc("tableofcontents");
638 BufferParams const & bufparams = buffer_->params();
639 const int min_toclevel = bufparams.documentClass().min_toclevel();
641 // For each paragraph, traverse its insets and let them add
643 ParagraphList & pars = paragraphs();
644 pit_type pend = paragraphs().size();
645 for (pit_type pit = 0; pit != pend; ++pit) {
646 Paragraph const & par = pars[pit];
648 // the string that goes to the toc (could be the optarg)
650 InsetList::const_iterator it = par.insetList().begin();
651 InsetList::const_iterator end = par.insetList().end();
652 for (; it != end; ++it) {
653 Inset & inset = *it->inset;
655 //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
657 switch (inset.lyxCode()) {
659 if (!tocstring.empty())
662 Paragraph const & insetpar =
663 *static_cast<InsetOptArg&>(inset).paragraphs().begin();
664 if (!par.labelString().empty())
665 tocstring = par.labelString() + ' ';
666 tocstring += insetpar.asString(AS_STR_INSETS);
673 // now the toc entry for the paragraph
674 int const toclevel = par.layout().toclevel;
675 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
677 // insert this into the table of contents
678 if (tocstring.empty())
679 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
680 toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
683 // And now the list of changes.
684 par.addChangesToToc(dit, buffer());
689 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
691 if (buffer().isClean())
692 return Inset::notifyCursorLeaves(old, cur);
694 // find text inset in old cursor
695 Cursor insetCur = old;
696 int scriptSlice = insetCur.find(this);
697 LASSERT(scriptSlice != -1, /**/);
698 insetCur.cutOff(scriptSlice);
699 LASSERT(&insetCur.inset() == this, /**/);
701 // update the old paragraph's words
702 insetCur.paragraph().updateWords();
704 return Inset::notifyCursorLeaves(old, cur);
708 bool InsetText::completionSupported(Cursor const & cur) const
710 //LASSERT(&cur.bv().cursor().inset() != this, return false);
711 return text_.completionSupported(cur);
715 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
717 return completionSupported(cur);
721 bool InsetText::automaticInlineCompletion() const
723 return lyxrc.completion_inline_text;
727 bool InsetText::automaticPopupCompletion() const
729 return lyxrc.completion_popup_text;
733 bool InsetText::showCompletionCursor() const
735 return lyxrc.completion_cursor_text;
739 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
741 return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
745 docstring InsetText::completionPrefix(Cursor const & cur) const
747 if (!completionSupported(cur))
749 return text_.completionPrefix(cur);
753 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
756 if (!completionSupported(cur))
759 return text_.insertCompletion(cur, s, finished);
763 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y,
764 Dimension & dim) const
766 TextMetrics const & tm = cur.bv().textMetrics(&text_);
767 tm.completionPosAndDim(cur, x, y, dim);
771 docstring InsetText::contextMenu(BufferView const &, int, int) const
773 return from_ascii("context-edit");
777 InsetCaption const * InsetText::getCaptionInset() const
779 ParagraphList::const_iterator pit = paragraphs().begin();
780 for (; pit != paragraphs().end(); ++pit) {
781 InsetList::const_iterator it = pit->insetList().begin();
782 for (; it != pit->insetList().end(); ++it) {
783 Inset & inset = *it->inset;
784 if (inset.lyxCode() == CAPTION_CODE) {
785 InsetCaption const * ins =
786 static_cast<InsetCaption const *>(it->inset);
795 docstring InsetText::getCaptionText(OutputParams const & runparams) const
797 InsetCaption const * ins = getCaptionInset();
801 odocstringstream ods;
802 ins->getCaptionAsPlaintext(ods, runparams);
807 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
809 InsetCaption const * ins = getCaptionInset();
813 odocstringstream ods;
814 docstring def = ins->getCaptionAsHTML(ods, runparams);