3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
16 #include "InsetMathBrace.h"
17 #include "InsetMathFont.h"
18 #include "InsetMathScript.h"
19 #include "MacroTable.h"
20 #include "MathMacro.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
23 #include "MetricsInfo.h"
24 #include "ReplaceData.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
31 #include "mathed/InsetMathUnknown.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
36 #include "frontends/FontMetrics.h"
37 #include "frontends/Painter.h"
39 #include <boost/assert.hpp>
40 #include <boost/next_prior.hpp>
49 MathData::MathData(const_iterator from, const_iterator to)
54 MathAtom & MathData::operator[](pos_type pos)
56 BOOST_ASSERT(pos < size());
57 return base_type::operator[](pos);
61 MathAtom const & MathData::operator[](pos_type pos) const
63 BOOST_ASSERT(pos < size());
64 return base_type::operator[](pos);
68 void MathData::insert(size_type pos, MathAtom const & t)
70 base_type::insert(begin() + pos, t);
74 void MathData::insert(size_type pos, MathData const & ar)
76 BOOST_ASSERT(pos <= size());
77 base_type::insert(begin() + pos, ar.begin(), ar.end());
81 void MathData::append(MathData const & ar)
87 void MathData::erase(size_type pos)
94 void MathData::erase(iterator pos1, iterator pos2)
96 base_type::erase(pos1, pos2);
100 void MathData::erase(iterator pos)
102 base_type::erase(pos);
106 void MathData::erase(size_type pos1, size_type pos2)
108 base_type::erase(begin() + pos1, begin() + pos2);
112 void MathData::dump2() const
116 for (const_iterator it = begin(); it != end(); ++it)
118 lyxerr << to_utf8(os.str());
122 void MathData::dump() const
126 for (const_iterator it = begin(); it != end(); ++it)
127 ns << '<' << *it << '>';
128 lyxerr << to_utf8(os.str());
132 void MathData::validate(LaTeXFeatures & features) const
134 for (const_iterator it = begin(); it != end(); ++it)
135 (*it)->validate(features);
139 bool MathData::match(MathData const & ar) const
141 return size() == ar.size() && matchpart(ar, 0);
145 bool MathData::matchpart(MathData const & ar, pos_type pos) const
147 if (size() < ar.size() + pos)
149 const_iterator it = begin() + pos;
150 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
151 if (asString(*it) != asString(*jt))
157 void MathData::replace(ReplaceData & rep)
159 for (size_type i = 0; i < size(); ++i) {
160 if (find1(rep.from, i)) {
162 lyxerr << "match found!" << endl;
163 erase(i, i + rep.from.size());
168 // FIXME: temporarily disabled
169 // for (const_iterator it = begin(); it != end(); ++it)
170 // it->nucleus()->replace(rep);
174 bool MathData::find1(MathData const & ar, size_type pos) const
176 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
177 for (size_type i = 0, n = ar.size(); i < n; ++i)
178 if (asString(operator[](pos + i)) != asString(ar[i]))
184 MathData::size_type MathData::find(MathData const & ar) const
186 for (int i = 0, last = size() - ar.size(); i < last; ++i)
193 MathData::size_type MathData::find_last(MathData const & ar) const
195 for (int i = size() - ar.size(); i >= 0; --i)
202 bool MathData::contains(MathData const & ar) const
204 if (find(ar) != size())
206 for (const_iterator it = begin(); it != end(); ++it)
207 if ((*it)->contains(ar))
213 void MathData::touch() const
220 bool isInside(DocIterator const & it, MathData const & ar,
221 pos_type p1, pos_type p2)
223 for (size_t i = 0; i != it.depth(); ++i) {
224 CursorSlice const & sl = it[i];
225 if (sl.inset().inMathed() && &sl.cell() == &ar)
226 return p1 <= sl.pos() && sl.pos() < p2;
235 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
237 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
238 dim = fm.dimension('I');
239 int xascent = fm.dimension('x').ascent();
240 if (xascent >= dim.asc)
241 xascent = (2 * dim.asc) / 3;
243 mindes_ = (3 * xascent) / 4;
244 slevel_ = (4 * xascent) / 5;
245 sshift_ = xascent / 4;
249 // Cache the dimension.
250 mi.base.bv->coordCache().arrays().add(this, dim);
254 Cursor & cur = mi.base.bv->cursor();
255 const_cast<MathData*>(this)->updateMacros(&cur, mi.macrocontext);
257 DocIterator const & inlineCompletionPos = mi.base.bv->inlineCompletionPos();
258 MathData const * inlineCompletionData = 0;
259 if (inlineCompletionPos.inMathed())
260 inlineCompletionData = &inlineCompletionPos.cell();
265 CoordCacheBase<Inset> & coords = mi.base.bv->coordCache().insets();
266 for (pos_type i = 0, n = size(); i != n; ++i) {
267 MathAtom const & at = operator[](i);
269 coords.add(at.nucleus(), d);
272 kerning_ = at->kerning(mi.base.bv);
274 // HACK to draw completion suggestion inline
275 if (inlineCompletionData != this
276 || size_t(inlineCompletionPos.pos()) != i + 1)
279 docstring const & completion = mi.base.bv->inlineCompletion();
280 if (completion.length() == 0)
283 dim.wid += mathed_string_width(mi.base.font, completion);
285 // Cache the dimension.
286 mi.base.bv->coordCache().arrays().add(this, dim);
290 void MathData::draw(PainterInfo & pi, int x, int y) const
292 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
293 BufferView & bv = *pi.base.bv;
296 Dimension const & dim = bv.coordCache().getArrays().dim(this);
299 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
303 // don't draw outside the workarea
304 if (y + dim.descent() <= 0
305 || y - dim.ascent() >= bv.workHeight()
306 || x + dim.width() <= 0
307 || x >= bv. workWidth())
310 DocIterator const & inlineCompletionPos = bv.inlineCompletionPos();
311 MathData const * inlineCompletionData = 0;
312 if (inlineCompletionPos.inMathed())
313 inlineCompletionData = &inlineCompletionPos.cell();
315 CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
316 for (size_t i = 0, n = size(); i != n; ++i) {
317 MathAtom const & at = operator[](i);
318 coords.add(at.nucleus(), x, y);
319 at->drawSelection(pi, x, y);
321 x += coords.dim(at.nucleus()).wid;
323 // Is the inline completion here?
324 if (inlineCompletionData != this
325 || size_t(inlineCompletionPos.pos()) != i + 1)
327 docstring const & completion = bv.inlineCompletion();
328 if (completion.length() == 0)
330 FontInfo f = pi.base.font;
332 // draw the unique and the non-unique completion part
333 // Note: this is not time-critical as it is
334 // only done once per screen.
335 size_t uniqueTo = bv.inlineCompletionUniqueChars();
336 docstring s1 = completion.substr(0, uniqueTo);
337 docstring s2 = completion.substr(uniqueTo);
340 f.setColor(Color_inlinecompletion);
341 pi.pain.text(x, y, s1, f);
342 x += mathed_string_width(f, s1);
346 f.setColor(Color_nonunique_inlinecompletion);
347 pi.pain.text(x, y, s2, f);
348 x += mathed_string_width(f, s2);
354 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
358 for (const_iterator it = begin(); it != end(); ++it) {
359 (*it)->metricsT(mi, d);
365 void MathData::drawT(TextPainter & pain, int x, int y) const
367 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
369 // FIXME: Abdel 16/10/2006
370 // This drawT() method is never used, this is dead code.
372 for (const_iterator it = begin(), et = end(); it != et; ++it) {
373 (*it)->drawT(pain, x, y);
374 //x += (*it)->width_;
380 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
382 // go over the array and look for macros
383 for (size_t i = 0; i < size(); ++i) {
384 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
389 macroInset->updateMacro(mc);
390 size_t macroNumArgs = 0;
391 size_t macroOptionals = 0;
392 MacroData const * macro = macroInset->macro();
394 macroNumArgs = macro->numargs();
395 macroOptionals = macro->optionals();
398 // store old and compute new display mode
399 MathMacro::DisplayMode newDisplayMode;
400 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
401 newDisplayMode = macroInset->computeDisplayMode();
403 // arity changed or other reason to detach?
404 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
405 && (macroInset->arity() != macroNumArgs
406 || macroInset->optionals() != macroOptionals
407 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
409 detachMacroParameters(cur, i);
412 // the macro could have been copied while resizing this
413 macroInset = operator[](i).nucleus()->asMacro();
416 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
417 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
418 // put cursor in front of macro
420 int macroSlice = cur->find(macroInset);
421 if (macroSlice != -1)
422 cur->cutOff(macroSlice - 1);
426 // update the display mode
427 macroInset->setDisplayMode(newDisplayMode);
430 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
431 && (macroInset->arity() != macroNumArgs
432 || macroInset->optionals() != macroOptionals)) {
433 // is it a virgin macro which was never attached to parameters?
434 bool fromInitToNormalMode
435 = (oldDisplayMode == MathMacro::DISPLAY_INIT
436 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
437 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
439 // if the macro was entered interactively (i.e. not by paste or during
440 // loading), it should not be greedy, but the cursor should
441 // automatically jump into the macro when behind
442 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
445 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
446 fromInitToNormalMode, interactive);
449 // FIXME: proper anchor handling, this removes the selection
450 cur->updateInsets(&cur->bottom().inset());
451 cur->clearSelection();
455 // Give macro the chance to adapt to new situation.
456 // The macroInset could be invalid now because it was put into a script
457 // inset and therefore "deep" copied. So get it again from the MathData.
458 InsetMath * inset = operator[](i).nucleus();
459 if (inset->asScriptInset())
460 inset = inset->asScriptInset()->nuc()[0].nucleus();
461 BOOST_ASSERT(inset->asMacro());
462 inset->asMacro()->updateRepresentation(cur);
467 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
469 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
471 // detach all arguments
472 vector<MathData> detachedArgs;
473 if (macroPos + 1 == size())
474 // strip arguments if we are at the MathData end
475 macroInset->detachArguments(detachedArgs, true);
477 macroInset->detachArguments(detachedArgs, false);
480 int curMacroSlice = -1;
482 curMacroSlice = cur->find(macroInset);
483 idx_type curMacroIdx = -1;
484 pos_type curMacroPos = -1;
485 vector<CursorSlice> argSlices;
486 if (curMacroSlice != -1) {
487 curMacroPos = (*cur)[curMacroSlice].pos();
488 curMacroIdx = (*cur)[curMacroSlice].idx();
489 cur->cutOff(curMacroSlice, argSlices);
493 // only [] after the last non-empty argument can be dropped later
494 size_t lastNonEmptyOptional = 0;
495 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
496 if (!detachedArgs[l].empty())
497 lastNonEmptyOptional = l;
500 // optional arguments to be put back?
501 pos_type p = macroPos + 1;
503 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
504 // another non-empty parameter follows?
505 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
507 // then we can drop empty optional parameters
508 if (detachedArgs[j].empty() && canDropEmptyOptional) {
509 if (curMacroIdx == j)
510 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
514 // Otherwise we don't drop an empty optional, put it back normally
516 asArray(from_ascii("[]"), optarg);
517 MathData & arg = detachedArgs[j];
519 // look for "]", i.e. put a brace around?
520 InsetMathBrace * brace = 0;
521 for (size_t q = 0; q < arg.size(); ++q) {
522 if (arg[q]->getChar() == ']') {
524 brace = new InsetMathBrace();
529 // put arg between []
531 brace->cell(0) = arg;
532 optarg.insert(1, MathAtom(brace));
534 optarg.insert(1, arg);
536 // insert it into the array
541 if (curMacroSlice == -1)
544 // cursor in optional argument of macro?
545 if (curMacroIdx == j) {
547 cur->append(0, curMacroPos);
548 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
550 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
551 cur->append(argSlices);
552 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
553 // cursor right of macro
554 (*cur)[curMacroSlice - 1].pos() += optarg.size();
557 // put them back into the MathData
558 for (; j < detachedArgs.size(); ++j, ++p) {
559 MathData const & arg = detachedArgs[j];
561 && !arg[0]->asScriptInset()
562 && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
565 insert(p, MathAtom(new InsetMathBrace(arg)));
568 if (curMacroSlice == -1)
571 // cursor in j-th argument of macro?
572 if (curMacroIdx == j) {
573 if (operator[](p).nucleus()->asBraceInset()) {
574 (*cur)[curMacroSlice - 1].pos() = p;
575 cur->append(0, curMacroPos);
576 cur->append(argSlices);
578 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
579 cur->append(argSlices);
581 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
582 ++(*cur)[curMacroSlice - 1].pos();
586 // FIXME: proper anchor handling, this removes the selection
587 cur->clearSelection();
588 cur->updateInsets(&cur->bottom().inset());
593 void MathData::attachMacroParameters(Cursor * cur,
594 const size_type macroPos, const size_type macroNumArgs,
595 const int macroOptionals, const bool fromInitToNormalMode,
596 const bool interactiveInit)
598 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
600 // start at atom behind the macro again, maybe with some new arguments
601 // from the detach phase above, to add them back into the macro inset
602 size_t p = macroPos + 1;
603 vector<MathData> detachedArgs;
604 MathAtom scriptToPutAround;
606 // find cursor slice again of this MathData
609 thisSlice = cur->find(*this);
612 thisPos = (*cur)[thisSlice].pos();
614 // find arguments behind the macro
615 if (!interactiveInit) {
616 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
617 scriptToPutAround, macroPos, thisPos, thisSlice);
618 collectParameters(cur, macroNumArgs, detachedArgs, p,
619 scriptToPutAround, macroPos, thisPos, thisSlice);
622 // attach arguments back to macro inset
623 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
625 // found tail script? E.g. \foo{a}b^x
626 if (scriptToPutAround.nucleus()) {
627 // put macro into a script inset
628 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
629 = operator[](macroPos);
630 operator[](macroPos) = scriptToPutAround;
632 // go into the script inset nucleus
633 if (cur && thisPos == int(macroPos))
636 // get pointer to "deep" copied macro inset
637 InsetMathScript * scriptInset
638 = operator[](macroPos).nucleus()->asScriptInset();
639 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
642 // remove them from the MathData
643 erase(begin() + macroPos + 1, begin() + p);
645 // cursor outside this MathData?
649 // fix cursor if right of p
650 if (thisPos >= int(p))
651 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
653 // was the macro inset just inserted interactively and was now folded
654 // and the cursor is just behind?
655 if ((*cur)[thisSlice].pos() == int(macroPos + 1)
657 && fromInitToNormalMode
658 && macroInset->arity() > 0
659 && thisSlice + 1 == int(cur->depth())) {
660 // then enter it if the cursor was just behind
661 (*cur)[thisSlice].pos() = macroPos;
662 cur->push_back(CursorSlice(*macroInset));
663 macroInset->idxFirst(*cur);
668 void MathData::collectOptionalParameters(Cursor * cur,
669 const size_type numOptionalParams, vector<MathData> & params,
670 size_t & pos, MathAtom & scriptToPutAround,
671 const pos_type macroPos, const int thisPos, const int thisSlice)
673 // insert optional arguments?
674 while (params.size() < numOptionalParams
676 && !scriptToPutAround.nucleus()) {
677 // is a [] block following which could be an optional parameter?
678 if (operator[](pos)->getChar() != '[')
681 // found possible optional argument, look for "]"
682 size_t right = pos + 1;
683 for (; right < size(); ++right) {
684 MathAtom & cell = operator[](right);
686 if (cell->getChar() == ']')
690 // maybe "]" with a script around?
691 InsetMathScript * script = cell.nucleus()->asScriptInset();
694 if (script->nuc().size() != 1)
696 if (script->nuc()[0]->getChar() == ']') {
697 // script will be put around the macro later
698 scriptToPutAround = cell;
704 if (right >= size()) {
705 // no ] found, so it's not an optional argument
709 // add everything between [ and ] as optional argument
710 MathData optarg(begin() + pos + 1, begin() + right);
714 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
716 params.push_back(optarg[0]->asBraceInset()->cell(0));
718 params.push_back(optarg);
720 // place cursor in optional argument of macro
722 && thisPos >= int(pos) && thisPos <= int(right)) {
723 int paramPos = max(0, thisPos - int(pos) - 1);
724 vector<CursorSlice> x;
725 cur->cutOff(thisSlice, x);
726 (*cur)[thisSlice].pos() = macroPos;
728 paramPos = x[0].pos();
731 cur->append(0, paramPos);
737 // fill up empty optional parameters
738 while (params.size() < numOptionalParams)
739 params.push_back(MathData());
743 void MathData::collectParameters(Cursor * cur,
744 const size_type numParams, vector<MathData> & params,
745 size_t & pos, MathAtom & scriptToPutAround,
746 const pos_type macroPos, const int thisPos, const int thisSlice)
748 // insert normal arguments
749 while (params.size() < numParams
751 && !scriptToPutAround.nucleus()) {
752 MathAtom & cell = operator[](pos);
755 vector<CursorSlice> argSlices;
757 if (thisSlice != -1 && thisPos == int(pos))
758 cur->cutOff(thisSlice, argSlices);
760 // which kind of parameter is it? In {}? With index x^n?
761 InsetMathBrace const * brace = cell->asBraceInset();
763 // found brace, convert into argument
764 params.push_back(brace->cell(0));
766 // cursor inside of the brace or just in front of?
767 if (thisPos == int(pos) && !argSlices.empty()) {
768 argPos = argSlices[0].pos();
769 argSlices.erase(argSlices.begin());
771 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
772 // last inset with scripts without braces
773 // -> they belong to the macro, not the argument
774 InsetMathScript * script = cell.nucleus()->asScriptInset();
775 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
776 // nucleus in brace? Unpack!
777 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
779 params.push_back(script->nuc());
781 // script will be put around below
782 scriptToPutAround = cell;
784 // this should only happen after loading, so make cursor handling simple
785 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
791 // the simplest case: plain inset
793 array.insert(0, cell);
794 params.push_back(array);
797 // put cursor in argument again
798 if (thisSlice != - 1 && thisPos == int(pos)) {
799 cur->append(params.size() - 1, argPos);
800 cur->append(argSlices);
801 (*cur)[thisSlice].pos() = macroPos;
809 int MathData::pos2x(BufferView const * bv, size_type pos) const
811 return pos2x(bv, pos, 0);
815 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
818 size_type target = min(pos, size());
819 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
820 for (size_type i = 0; i < target; ++i) {
821 const_iterator it = begin() + i;
822 if ((*it)->getChar() == ' ')
824 //lyxerr << "char: " << (*it)->getChar()
825 // << "width: " << (*it)->width() << endl;
826 x += coords.dim((*it).nucleus()).wid;
832 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
834 return x2pos(bv, targetx, 0);
838 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
840 const_iterator it = begin();
843 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
844 // find first position after targetx
845 for (; currx < targetx && it < end(); ++it) {
847 if ((*it)->getChar() == ' ')
849 currx += coords.dim((*it).nucleus()).wid;
853 * If we are not at the beginning of the array, go to the left
854 * of the inset if one of the following two condition holds:
855 * - the current inset is editable (so that the cursor tip is
856 * deeper than us): in this case, we want all intermediate
857 * cursor slices to be before insets;
858 * - the mouse is closer to the left side of the inset than to
860 * See bug 1918 for details.
862 if (it != begin() && currx >= targetx
863 && ((*boost::prior(it))->asNestInset()
864 || abs(lastx - targetx) < abs(currx - targetx))) {
872 int MathData::dist(BufferView const & bv, int x, int y) const
874 return bv.coordCache().getArrays().squareDistance(this, x, y);
878 void MathData::setXY(BufferView & bv, int x, int y) const
880 //lyxerr << "setting position cache for MathData " << this << endl;
881 bv.coordCache().arrays().add(this, x, y);
885 Dimension const & MathData::dimension(BufferView const & bv) const
887 return bv.coordCache().getArrays().dim(this);
891 int MathData::xm(BufferView const & bv) const
893 Geometry const & g = bv.coordCache().getArrays().geometry(this);
895 return g.pos.x_ + g.dim.wid / 2;
899 int MathData::ym(BufferView const & bv) const
901 Geometry const & g = bv.coordCache().getArrays().geometry(this);
903 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
907 int MathData::xo(BufferView const & bv) const
909 return bv.coordCache().getArrays().x(this);
913 int MathData::yo(BufferView const & bv) const
915 return bv.coordCache().getArrays().y(this);
919 ostream & operator<<(ostream & os, MathData const & ar)
921 odocstringstream oss;
922 NormalStream ns(oss);
924 return os << to_utf8(oss.str());
928 odocstream & operator<<(odocstream & os, MathData const & ar)