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 "support/debug.h"
32 #include "support/docstream.h"
34 #include "frontends/FontMetrics.h"
35 #include "frontends/Painter.h"
37 #include <boost/assert.hpp>
38 #include <boost/next_prior.hpp>
47 MathData::MathData(const_iterator from, const_iterator to)
52 MathAtom & MathData::operator[](pos_type pos)
54 BOOST_ASSERT(pos < size());
55 return base_type::operator[](pos);
59 MathAtom const & MathData::operator[](pos_type pos) const
61 BOOST_ASSERT(pos < size());
62 return base_type::operator[](pos);
66 void MathData::insert(size_type pos, MathAtom const & t)
68 base_type::insert(begin() + pos, t);
72 void MathData::insert(size_type pos, MathData const & ar)
74 BOOST_ASSERT(pos <= size());
75 base_type::insert(begin() + pos, ar.begin(), ar.end());
79 void MathData::append(MathData const & ar)
85 void MathData::erase(size_type pos)
92 void MathData::erase(iterator pos1, iterator pos2)
94 base_type::erase(pos1, pos2);
98 void MathData::erase(iterator pos)
100 base_type::erase(pos);
104 void MathData::erase(size_type pos1, size_type pos2)
106 base_type::erase(begin() + pos1, begin() + pos2);
110 void MathData::dump2() const
114 for (const_iterator it = begin(); it != end(); ++it)
116 lyxerr << to_utf8(os.str());
120 void MathData::dump() const
124 for (const_iterator it = begin(); it != end(); ++it)
125 ns << '<' << *it << '>';
126 lyxerr << to_utf8(os.str());
130 void MathData::validate(LaTeXFeatures & features) const
132 for (const_iterator it = begin(); it != end(); ++it)
133 (*it)->validate(features);
137 bool MathData::match(MathData const & ar) const
139 return size() == ar.size() && matchpart(ar, 0);
143 bool MathData::matchpart(MathData const & ar, pos_type pos) const
145 if (size() < ar.size() + pos)
147 const_iterator it = begin() + pos;
148 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
149 if (asString(*it) != asString(*jt))
155 void MathData::replace(ReplaceData & rep)
157 for (size_type i = 0; i < size(); ++i) {
158 if (find1(rep.from, i)) {
160 lyxerr << "match found!" << endl;
161 erase(i, i + rep.from.size());
166 // FIXME: temporarily disabled
167 // for (const_iterator it = begin(); it != end(); ++it)
168 // it->nucleus()->replace(rep);
172 bool MathData::find1(MathData const & ar, size_type pos) const
174 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
175 for (size_type i = 0, n = ar.size(); i < n; ++i)
176 if (asString(operator[](pos + i)) != asString(ar[i]))
182 MathData::size_type MathData::find(MathData const & ar) const
184 for (int i = 0, last = size() - ar.size(); i < last; ++i)
191 MathData::size_type MathData::find_last(MathData const & ar) const
193 for (int i = size() - ar.size(); i >= 0; --i)
200 bool MathData::contains(MathData const & ar) const
202 if (find(ar) != size())
204 for (const_iterator it = begin(); it != end(); ++it)
205 if ((*it)->contains(ar))
211 void MathData::touch() const
218 bool isInside(DocIterator const & it, MathData const & ar,
219 pos_type p1, pos_type p2)
221 for (size_t i = 0; i != it.depth(); ++i) {
222 CursorSlice const & sl = it[i];
223 if (sl.inset().inMathed() && &sl.cell() == &ar)
224 return p1 <= sl.pos() && sl.pos() < p2;
233 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
235 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
236 dim = fm.dimension('I');
237 int xascent = fm.dimension('x').ascent();
238 if (xascent >= dim.asc)
239 xascent = (2 * dim.asc) / 3;
241 mindes_ = (3 * xascent) / 4;
242 slevel_ = (4 * xascent) / 5;
243 sshift_ = xascent / 4;
247 // Cache the dimension.
248 mi.base.bv->coordCache().arrays().add(this, dim);
252 Cursor & cur = mi.base.bv->cursor();
253 const_cast<MathData*>(this)->updateMacros(&cur, mi.macrocontext);
258 CoordCacheBase<Inset> & coords = mi.base.bv->coordCache().insets();
259 for (size_t i = 0, n = size(); i != n; ++i) {
260 MathAtom const & at = operator[](i);
262 coords.add(at.nucleus(), d);
265 kerning_ = at->kerning(mi.base.bv);
267 // Cache the dimension.
268 mi.base.bv->coordCache().arrays().add(this, dim);
272 void MathData::draw(PainterInfo & pi, int x, int y) const
274 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
275 BufferView & bv = *pi.base.bv;
278 Dimension const & dim = bv.coordCache().getArrays().dim(this);
281 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
285 // don't draw outside the workarea
286 if (y + dim.descent() <= 0
287 || y - dim.ascent() >= bv.workHeight()
288 || x + dim.width() <= 0
289 || x >= bv. workWidth())
292 CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
293 for (size_t i = 0, n = size(); i != n; ++i) {
294 MathAtom const & at = operator[](i);
295 coords.add(at.nucleus(), x, y);
296 at->drawSelection(pi, x, y);
298 x += coords.dim(at.nucleus()).wid;
303 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
307 for (const_iterator it = begin(); it != end(); ++it) {
308 (*it)->metricsT(mi, d);
314 void MathData::drawT(TextPainter & pain, int x, int y) const
316 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
318 // FIXME: Abdel 16/10/2006
319 // This drawT() method is never used, this is dead code.
321 for (const_iterator it = begin(), et = end(); it != et; ++it) {
322 (*it)->drawT(pain, x, y);
323 //x += (*it)->width_;
329 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
331 // go over the array and look for macros
332 for (size_t i = 0; i < size(); ++i) {
333 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
338 macroInset->updateMacro(mc);
339 size_t macroNumArgs = 0;
340 size_t macroOptionals = 0;
341 MacroData const * macro = macroInset->macro();
343 macroNumArgs = macro->numargs();
344 macroOptionals = macro->optionals();
347 // store old and compute new display mode
348 MathMacro::DisplayMode newDisplayMode;
349 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
350 newDisplayMode = macroInset->computeDisplayMode();
352 // arity changed or other reason to detach?
353 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
354 && (macroInset->arity() != macroNumArgs
355 || macroInset->optionals() != macroOptionals
356 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
358 detachMacroParameters(cur, i);
361 // the macro could have been copied while resizing this
362 macroInset = operator[](i).nucleus()->asMacro();
365 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
366 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
367 // put cursor in front of macro
369 int macroSlice = cur->find(macroInset);
370 if (macroSlice != -1)
371 cur->cutOff(macroSlice - 1);
375 // update the display mode
376 macroInset->setDisplayMode(newDisplayMode);
379 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
380 && (macroInset->arity() != macroNumArgs
381 || macroInset->optionals() != macroOptionals)) {
382 // is it a virgin macro which was never attached to parameters?
383 bool fromInitToNormalMode
384 = (oldDisplayMode == MathMacro::DISPLAY_INIT
385 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
386 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
388 // if the macro was entered interactively (i.e. not by paste or during
389 // loading), it should not be greedy, but the cursor should
390 // automatically jump into the macro when behind
391 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
394 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
395 fromInitToNormalMode, interactive);
398 // FIXME: proper anchor handling, this removes the selection
399 cur->updateInsets(&cur->bottom().inset());
400 cur->clearSelection();
404 // Give macro the chance to adapt to new situation.
405 // The macroInset could be invalid now because it was put into a script
406 // inset and therefore "deep" copied. So get it again from the MathData.
407 InsetMath * inset = operator[](i).nucleus();
408 if (inset->asScriptInset())
409 inset = inset->asScriptInset()->nuc()[0].nucleus();
410 BOOST_ASSERT(inset->asMacro());
411 inset->asMacro()->updateRepresentation(cur);
416 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
418 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
420 // detach all arguments
421 vector<MathData> detachedArgs;
422 if (macroPos + 1 == size())
423 // strip arguments if we are at the MathData end
424 macroInset->detachArguments(detachedArgs, true);
426 macroInset->detachArguments(detachedArgs, false);
429 int curMacroSlice = -1;
431 curMacroSlice = cur->find(macroInset);
432 idx_type curMacroIdx = -1;
433 pos_type curMacroPos = -1;
434 vector<CursorSlice> argSlices;
435 if (curMacroSlice != -1) {
436 curMacroPos = (*cur)[curMacroSlice].pos();
437 curMacroIdx = (*cur)[curMacroSlice].idx();
438 cur->cutOff(curMacroSlice, argSlices);
442 // only [] after the last non-empty argument can be dropped later
443 size_t lastNonEmptyOptional = 0;
444 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
445 if (!detachedArgs[l].empty())
446 lastNonEmptyOptional = l;
449 // optional arguments to be put back?
450 pos_type p = macroPos + 1;
452 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
453 // another non-empty parameter follows?
454 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
456 // then we can drop empty optional parameters
457 if (detachedArgs[j].empty() && canDropEmptyOptional) {
458 if (curMacroIdx == j)
459 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
463 // Otherwise we don't drop an empty optional, put it back normally
465 asArray(from_ascii("[]"), optarg);
466 MathData & arg = detachedArgs[j];
468 // look for "]", i.e. put a brace around?
469 InsetMathBrace * brace = 0;
470 for (size_t q = 0; q < arg.size(); ++q) {
471 if (arg[q]->getChar() == ']') {
473 brace = new InsetMathBrace();
478 // put arg between []
480 brace->cell(0) = arg;
481 optarg.insert(1, MathAtom(brace));
483 optarg.insert(1, arg);
485 // insert it into the array
490 if (curMacroSlice == -1)
493 // cursor in optional argument of macro?
494 if (curMacroIdx == j) {
496 cur->append(0, curMacroPos);
497 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
499 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
500 cur->append(argSlices);
501 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
502 // cursor right of macro
503 (*cur)[curMacroSlice - 1].pos() += optarg.size();
506 // put them back into the MathData
507 for (; j < detachedArgs.size(); ++j, ++p) {
508 MathData const & arg = detachedArgs[j];
510 && !arg[0]->asScriptInset()
511 && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
514 insert(p, MathAtom(new InsetMathBrace(arg)));
517 if (curMacroSlice == -1)
520 // cursor in j-th argument of macro?
521 if (curMacroIdx == j) {
522 if (operator[](p).nucleus()->asBraceInset()) {
523 (*cur)[curMacroSlice - 1].pos() = p;
524 cur->append(0, curMacroPos);
525 cur->append(argSlices);
527 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
528 cur->append(argSlices);
530 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
531 ++(*cur)[curMacroSlice - 1].pos();
535 // FIXME: proper anchor handling, this removes the selection
536 cur->clearSelection();
537 cur->updateInsets(&cur->bottom().inset());
542 void MathData::attachMacroParameters(Cursor * cur,
543 const size_type macroPos, const size_type macroNumArgs,
544 const int macroOptionals, const bool fromInitToNormalMode,
545 const bool interactiveInit)
547 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
549 // start at atom behind the macro again, maybe with some new arguments
550 // from the detach phase above, to add them back into the macro inset
551 size_t p = macroPos + 1;
552 vector<MathData> detachedArgs;
553 MathAtom scriptToPutAround;
555 // find cursor slice again of this MathData
558 thisSlice = cur->find(*this);
561 thisPos = (*cur)[thisSlice].pos();
563 // find arguments behind the macro
564 if (!interactiveInit) {
565 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
566 scriptToPutAround, macroPos, thisPos, thisSlice);
567 collectParameters(cur, macroNumArgs, detachedArgs, p,
568 scriptToPutAround, macroPos, thisPos, thisSlice);
571 // attach arguments back to macro inset
572 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
574 // found tail script? E.g. \foo{a}b^x
575 if (scriptToPutAround.nucleus()) {
576 // put macro into a script inset
577 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
578 = operator[](macroPos);
579 operator[](macroPos) = scriptToPutAround;
581 // go into the script inset nucleus
582 if (cur && thisPos == int(macroPos))
585 // get pointer to "deep" copied macro inset
586 InsetMathScript * scriptInset
587 = operator[](macroPos).nucleus()->asScriptInset();
588 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
591 // remove them from the MathData
592 erase(begin() + macroPos + 1, begin() + p);
594 // cursor outside this MathData?
598 // fix cursor if right of p
599 if (thisPos >= int(p))
600 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
602 // was the macro inset just inserted interactively and was now folded
603 // and the cursor is just behind?
604 if ((*cur)[thisSlice].pos() == int(macroPos + 1)
606 && fromInitToNormalMode
607 && macroInset->arity() > 0
608 && thisSlice + 1 == int(cur->depth())) {
609 // then enter it if the cursor was just behind
610 (*cur)[thisSlice].pos() = macroPos;
611 cur->push_back(CursorSlice(*macroInset));
612 macroInset->idxFirst(*cur);
617 void MathData::collectOptionalParameters(Cursor * cur,
618 const size_type numOptionalParams, vector<MathData> & params,
619 size_t & pos, MathAtom & scriptToPutAround,
620 const pos_type macroPos, const int thisPos, const int thisSlice)
622 // insert optional arguments?
623 while (params.size() < numOptionalParams
625 && !scriptToPutAround.nucleus()) {
626 // is a [] block following which could be an optional parameter?
627 if (operator[](pos)->getChar() != '[')
630 // found possible optional argument, look for "]"
631 size_t right = pos + 1;
632 for (; right < size(); ++right) {
633 MathAtom & cell = operator[](right);
635 if (cell->getChar() == ']')
639 // maybe "]" with a script around?
640 InsetMathScript * script = cell.nucleus()->asScriptInset();
643 if (script->nuc().size() != 1)
645 if (script->nuc()[0]->getChar() == ']') {
646 // script will be put around the macro later
647 scriptToPutAround = cell;
653 if (right >= size()) {
654 // no ] found, so it's not an optional argument
658 // add everything between [ and ] as optional argument
659 MathData optarg(begin() + pos + 1, begin() + right);
663 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
665 params.push_back(optarg[0]->asBraceInset()->cell(0));
667 params.push_back(optarg);
669 // place cursor in optional argument of macro
671 && thisPos >= int(pos) && thisPos <= int(right)) {
672 int paramPos = max(0, thisPos - int(pos) - 1);
673 vector<CursorSlice> x;
674 cur->cutOff(thisSlice, x);
675 (*cur)[thisSlice].pos() = macroPos;
677 paramPos = x[0].pos();
680 cur->append(0, paramPos);
686 // fill up empty optional parameters
687 while (params.size() < numOptionalParams)
688 params.push_back(MathData());
692 void MathData::collectParameters(Cursor * cur,
693 const size_type numParams, vector<MathData> & params,
694 size_t & pos, MathAtom & scriptToPutAround,
695 const pos_type macroPos, const int thisPos, const int thisSlice)
697 // insert normal arguments
698 while (params.size() < numParams
700 && !scriptToPutAround.nucleus()) {
701 MathAtom & cell = operator[](pos);
704 vector<CursorSlice> argSlices;
706 if (thisSlice != -1 && thisPos == int(pos))
707 cur->cutOff(thisSlice, argSlices);
709 // which kind of parameter is it? In {}? With index x^n?
710 InsetMathBrace const * brace = cell->asBraceInset();
712 // found brace, convert into argument
713 params.push_back(brace->cell(0));
715 // cursor inside of the brace or just in front of?
716 if (thisPos == int(pos) && !argSlices.empty()) {
717 argPos = argSlices[0].pos();
718 argSlices.erase(argSlices.begin());
720 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
721 // last inset with scripts without braces
722 // -> they belong to the macro, not the argument
723 InsetMathScript * script = cell.nucleus()->asScriptInset();
724 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
725 // nucleus in brace? Unpack!
726 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
728 params.push_back(script->nuc());
730 // script will be put around below
731 scriptToPutAround = cell;
733 // this should only happen after loading, so make cursor handling simple
734 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
740 // the simplest case: plain inset
742 array.insert(0, cell);
743 params.push_back(array);
746 // put cursor in argument again
747 if (thisSlice != - 1 && thisPos == int(pos)) {
748 cur->append(params.size() - 1, argPos);
749 cur->append(argSlices);
750 (*cur)[thisSlice].pos() = macroPos;
758 int MathData::pos2x(BufferView const * bv, size_type pos) const
760 return pos2x(bv, pos, 0);
764 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
767 size_type target = min(pos, size());
768 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
769 for (size_type i = 0; i < target; ++i) {
770 const_iterator it = begin() + i;
771 if ((*it)->getChar() == ' ')
773 //lyxerr << "char: " << (*it)->getChar()
774 // << "width: " << (*it)->width() << endl;
775 x += coords.dim((*it).nucleus()).wid;
781 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
783 return x2pos(bv, targetx, 0);
787 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
789 const_iterator it = begin();
792 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
793 // find first position after targetx
794 for (; currx < targetx && it < end(); ++it) {
796 if ((*it)->getChar() == ' ')
798 currx += coords.dim((*it).nucleus()).wid;
802 * If we are not at the beginning of the array, go to the left
803 * of the inset if one of the following two condition holds:
804 * - the current inset is editable (so that the cursor tip is
805 * deeper than us): in this case, we want all intermediate
806 * cursor slices to be before insets;
807 * - the mouse is closer to the left side of the inset than to
809 * See bug 1918 for details.
811 if (it != begin() && currx >= targetx
812 && ((*boost::prior(it))->asNestInset()
813 || abs(lastx - targetx) < abs(currx - targetx))) {
821 int MathData::dist(BufferView const & bv, int x, int y) const
823 return bv.coordCache().getArrays().squareDistance(this, x, y);
827 void MathData::setXY(BufferView & bv, int x, int y) const
829 //lyxerr << "setting position cache for MathData " << this << endl;
830 bv.coordCache().arrays().add(this, x, y);
834 Dimension const & MathData::dimension(BufferView const & bv) const
836 return bv.coordCache().getArrays().dim(this);
840 int MathData::xm(BufferView const & bv) const
842 Geometry const & g = bv.coordCache().getArrays().geometry(this);
844 return g.pos.x_ + g.dim.wid / 2;
848 int MathData::ym(BufferView const & bv) const
850 Geometry const & g = bv.coordCache().getArrays().geometry(this);
852 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
856 int MathData::xo(BufferView const & bv) const
858 return bv.coordCache().getArrays().x(this);
862 int MathData::yo(BufferView const & bv) const
864 return bv.coordCache().getArrays().y(this);
868 ostream & operator<<(ostream & os, MathData const & ar)
870 odocstringstream oss;
871 NormalStream ns(oss);
873 return os << to_utf8(oss.str());
877 odocstream & operator<<(odocstream & os, MathData const & ar)