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"
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>
46 using std::ostringstream;
51 MathData::MathData(const_iterator from, const_iterator to)
56 MathAtom & MathData::operator[](pos_type pos)
58 BOOST_ASSERT(pos < size());
59 return base_type::operator[](pos);
63 MathAtom const & MathData::operator[](pos_type pos) const
65 BOOST_ASSERT(pos < size());
66 return base_type::operator[](pos);
70 void MathData::insert(size_type pos, MathAtom const & t)
72 base_type::insert(begin() + pos, t);
76 void MathData::insert(size_type pos, MathData const & ar)
78 BOOST_ASSERT(pos <= size());
79 base_type::insert(begin() + pos, ar.begin(), ar.end());
83 void MathData::append(MathData const & ar)
89 void MathData::erase(size_type pos)
96 void MathData::erase(iterator pos1, iterator pos2)
98 base_type::erase(pos1, pos2);
102 void MathData::erase(iterator pos)
104 base_type::erase(pos);
108 void MathData::erase(size_type pos1, size_type pos2)
110 base_type::erase(begin() + pos1, begin() + pos2);
114 void MathData::dump2() const
118 for (const_iterator it = begin(); it != end(); ++it)
120 lyxerr << to_utf8(os.str());
124 void MathData::dump() const
128 for (const_iterator it = begin(); it != end(); ++it)
129 ns << '<' << *it << '>';
130 lyxerr << to_utf8(os.str());
134 void MathData::validate(LaTeXFeatures & features) const
136 for (const_iterator it = begin(); it != end(); ++it)
137 (*it)->validate(features);
141 bool MathData::match(MathData const & ar) const
143 return size() == ar.size() && matchpart(ar, 0);
147 bool MathData::matchpart(MathData const & ar, pos_type pos) const
149 if (size() < ar.size() + pos)
151 const_iterator it = begin() + pos;
152 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
153 if (asString(*it) != asString(*jt))
159 void MathData::replace(ReplaceData & rep)
161 for (size_type i = 0; i < size(); ++i) {
162 if (find1(rep.from, i)) {
164 lyxerr << "match found!" << endl;
165 erase(i, i + rep.from.size());
170 // FIXME: temporarily disabled
171 // for (const_iterator it = begin(); it != end(); ++it)
172 // it->nucleus()->replace(rep);
176 bool MathData::find1(MathData const & ar, size_type pos) const
178 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
179 for (size_type i = 0, n = ar.size(); i < n; ++i)
180 if (asString(operator[](pos + i)) != asString(ar[i]))
186 MathData::size_type MathData::find(MathData const & ar) const
188 for (int i = 0, last = size() - ar.size(); i < last; ++i)
195 MathData::size_type MathData::find_last(MathData const & ar) const
197 for (int i = size() - ar.size(); i >= 0; --i)
204 bool MathData::contains(MathData const & ar) const
206 if (find(ar) != size())
208 for (const_iterator it = begin(); it != end(); ++it)
209 if ((*it)->contains(ar))
215 void MathData::touch() const
222 bool isInside(DocIterator const & it, MathData const & ar,
223 pos_type p1, pos_type p2)
225 for (size_t i = 0; i != it.depth(); ++i) {
226 CursorSlice const & sl = it[i];
227 if (sl.inset().inMathed() && &sl.cell() == &ar)
228 return p1 <= sl.pos() && sl.pos() < p2;
237 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
239 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
240 dim = fm.dimension('I');
241 int xascent = fm.dimension('x').ascent();
242 if (xascent >= dim.asc)
243 xascent = (2 * dim.asc) / 3;
245 mindes_ = (3 * xascent) / 4;
246 slevel_ = (4 * xascent) / 5;
247 sshift_ = xascent / 4;
251 // Cache the dimension.
252 mi.base.bv->coordCache().arrays().add(this, dim);
256 const_cast<MathData*>(this)->updateMacros(mi);
262 for (size_t i = 0, n = size(); i != n; ++i) {
263 MathAtom const & at = operator[](i);
265 atom_dims_.push_back(d);
268 kerning_ = at->kerning();
270 // Cache the dimension.
271 mi.base.bv->coordCache().arrays().add(this, dim);
275 void MathData::draw(PainterInfo & pi, int x, int y) const
277 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
278 BufferView & bv = *pi.base.bv;
281 Dimension const & dim = bv.coordCache().getArrays().dim(this);
284 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
288 // don't draw outside the workarea
289 if (y + dim.descent() <= 0
290 || y - dim.ascent() >= bv.workHeight()
291 || x + dim.width() <= 0
292 || x >= bv. workWidth())
295 for (size_t i = 0, n = size(); i != n; ++i) {
296 MathAtom const & at = operator[](i);
297 bv.coordCache().insets().add(at.nucleus(), x, y);
298 at->drawSelection(pi, x, y);
300 x += atom_dims_[i].wid;
305 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
309 for (const_iterator it = begin(); it != end(); ++it) {
310 (*it)->metricsT(mi, d);
316 void MathData::drawT(TextPainter & pain, int x, int y) const
318 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
320 // FIXME: Abdel 16/10/2006
321 // This drawT() method is never used, this is dead code.
323 for (const_iterator it = begin(), et = end(); it != et; ++it) {
324 (*it)->drawT(pain, x, y);
325 //x += (*it)->width_;
331 void MathData::updateMacros(MetricsInfo & mi)
333 Cursor & cur = mi.base.bv->cursor();
335 // go over the array and look for macros
336 for (size_t i = 0; i < size(); ++i) {
337 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
342 macroInset->updateMacro(mi);
343 size_t macroNumArgs = 0;
344 size_t macroOptionals = 0;
345 MacroData const * macro = macroInset->macro();
347 macroNumArgs = macro->numargs();
348 macroOptionals = macro->optionals();
351 // store old and compute new display mode
352 MathMacro::DisplayMode newDisplayMode;
353 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
354 newDisplayMode = macroInset->computeDisplayMode(mi);
356 // arity changed or other reason to detach?
357 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
358 && (macroInset->arity() != macroNumArgs
359 || macroInset->optionals() != macroOptionals
360 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
361 detachMacroParameters(cur, i);
364 // the macro could have been copied while resizing this
365 macroInset = operator[](i).nucleus()->asMacro();
368 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
369 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
370 // put cursor in front of macro
371 int macroSlice = cur.find(macroInset);
372 if (macroSlice != -1)
373 cur.cutOff(macroSlice - 1);
376 // update the display mode
377 macroInset->setDisplayMode(newDisplayMode);
380 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
381 && (macroInset->arity() != macroNumArgs
382 || macroInset->optionals() != macroOptionals)) {
383 // is it a virgin macro which was never attached to parameters?
384 bool fromInitToNormalMode
385 = (oldDisplayMode == MathMacro::DISPLAY_INIT
386 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
387 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
389 // if the macro was entered interactively (i.e. not by paste or during
390 // loading), it should not be greedy, but the cursor should
391 // automatically jump into the macro when behind
392 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
395 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
396 fromInitToNormalMode, interactive);
398 // FIXME: proper anchor handling, this removes the selection
399 cur.updateInsets(&cur.bottom().inset());
400 cur.clearSelection();
403 // Give macro the chance to adapt to new situation.
404 // The macroInset could be invalid now because it was put into a script
405 // inset and therefore "deep" copied. So get it again from the MathData.
406 InsetMath * inset = operator[](i).nucleus();
407 if (inset->asScriptInset())
408 inset = inset->asScriptInset()->nuc()[0].nucleus();
409 BOOST_ASSERT(inset->asMacro());
410 inset->asMacro()->updateRepresentation(mi);
415 void MathData::detachMacroParameters(Cursor & cur, const size_type macroPos)
417 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
419 // detach all arguments
420 std::vector<MathData> detachedArgs;
421 if (macroPos + 1 == size())
422 // strip arguments if we are at the MathData end
423 macroInset->detachArguments(detachedArgs, true);
425 macroInset->detachArguments(detachedArgs, false);
428 int curMacroSlice = cur.find(macroInset);
429 idx_type curMacroIdx = -1;
430 pos_type curMacroPos = -1;
431 std::vector<CursorSlice> argSlices;
432 if (curMacroSlice != -1) {
433 curMacroPos = cur[curMacroSlice].pos();
434 curMacroIdx = cur[curMacroSlice].idx();
435 cur.cutOff(curMacroSlice, argSlices);
439 // only [] after the last non-empty argument can be dropped later
440 size_t lastNonEmptyOptional = 0;
441 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
442 if (!detachedArgs[l].empty())
443 lastNonEmptyOptional = l;
446 // optional arguments to be put back?
447 pos_type p = macroPos + 1;
449 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
450 // another non-empty parameter follows?
451 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
453 // then we can drop empty optional parameters
454 if (detachedArgs[j].empty() && canDropEmptyOptional) {
455 if (curMacroIdx == j)
456 cur[curMacroSlice - 1].pos() = macroPos + 1;
460 // Otherwise we don't drop an empty optional, put it back normally
462 asArray(from_ascii("[]"), optarg);
463 MathData & arg = detachedArgs[j];
465 // look for "]", i.e. put a brace around?
466 InsetMathBrace * brace = 0;
467 for (size_t q = 0; q < arg.size(); ++q) {
468 if (arg[q]->getChar() == ']') {
470 brace = new InsetMathBrace();
475 // put arg between []
477 brace->cell(0) = arg;
478 optarg.insert(1, MathAtom(brace));
480 optarg.insert(1, arg);
482 // insert it into the array
487 if (curMacroSlice == -1)
490 // cursor in optional argument of macro?
491 if (curMacroIdx == j) {
493 cur.append(0, curMacroPos);
494 cur[curMacroSlice - 1].pos() = macroPos + 2;
496 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
497 cur.append(argSlices);
498 } else if (cur[curMacroSlice - 1].pos() >= int(p))
499 // cursor right of macro
500 cur[curMacroSlice - 1].pos() += optarg.size();
503 // put them back into the MathData
504 for (; j < detachedArgs.size(); ++j, ++p) {
505 MathData const & arg = detachedArgs[j];
506 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
509 insert(p, MathAtom(new InsetMathBrace(arg)));
512 if (curMacroSlice == -1)
515 // cursor in j-th argument of macro?
516 if (curMacroIdx == j) {
517 if (operator[](p).nucleus()->asBraceInset()) {
518 cur[curMacroSlice - 1].pos() = p;
519 cur.append(0, curMacroPos);
520 cur.append(argSlices);
522 cur[curMacroSlice - 1].pos() = p; // + macroPos;
523 cur.append(argSlices);
525 } else if (cur[curMacroSlice - 1].pos() >= int(p))
526 ++cur[curMacroSlice - 1].pos();
529 // FIXME: proper anchor handling, this removes the selection
530 cur.clearSelection();
531 cur.updateInsets(&cur.bottom().inset());
535 void MathData::attachMacroParameters(Cursor & cur,
536 const size_type macroPos, const size_type macroNumArgs,
537 const int macroOptionals, const bool fromInitToNormalMode,
538 const bool interactiveInit)
540 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
542 // start at atom behind the macro again, maybe with some new arguments
543 // from the detach phase above, to add them back into the macro inset
544 size_t p = macroPos + 1;
545 std::vector<MathData> detachedArgs;
546 MathAtom scriptToPutAround;
548 // find cursor slice again of this MathData
549 int thisSlice = cur.find(*this);
552 thisPos = cur[thisSlice].pos();
554 // find arguments behind the macro
555 if (!interactiveInit) {
556 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
557 macroPos, thisPos, thisSlice);
558 collectParameters(cur, macroNumArgs, detachedArgs, p,
559 scriptToPutAround, macroPos, thisPos, thisSlice);
562 // attach arguments back to macro inset
563 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
565 // found tail script? E.g. \foo{a}b^x
566 if (scriptToPutAround.nucleus()) {
567 // put macro into a script inset
568 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
569 = operator[](macroPos);
570 operator[](macroPos) = scriptToPutAround;
572 // go into the script inset nucleus
573 if (thisPos == int(macroPos))
576 // get pointer to "deep" copied macro inset
577 InsetMathScript * scriptInset
578 = operator[](macroPos).nucleus()->asScriptInset();
579 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
582 // remove them from the MathData
583 erase(begin() + macroPos + 1, begin() + p);
585 // cursor outside this MathData?
589 // fix cursor if right of p
590 if (thisPos >= int(p))
591 cur[thisSlice].pos() -= p - (macroPos + 1);
593 // was the macro inset just inserted interactively and was now folded
594 // and the cursor is just behind?
595 if (cur[thisSlice].pos() == int(macroPos + 1)
597 && fromInitToNormalMode
598 && macroInset->arity() > 0
599 && thisSlice + 1 == int(cur.depth())) {
600 // then enter it if the cursor was just behind
601 cur[thisSlice].pos() = macroPos;
602 cur.push_back(CursorSlice(*macroInset));
603 macroInset->idxFirst(cur);
608 void MathData::collectOptionalParameters(Cursor & cur,
609 const size_type numOptionalParams, std::vector<MathData> & params,
610 size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
612 // insert optional arguments?
613 while (params.size() < numOptionalParams && pos < size()) {
614 // is a [] block following which could be an optional parameter?
615 if (operator[](pos)->getChar() != '[')
618 // found possible optional argument, look for "]"
619 size_t right = pos + 1;
620 for (; right < size(); ++right) {
621 if (operator[](right)->getChar() == ']')
627 if (right >= size()) {
628 // no ] found, so it's not an optional argument
632 // add everything between [ and ] as optional argument
633 MathData optarg(begin() + pos + 1, begin() + right);
637 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
639 params.push_back(optarg[0]->asBraceInset()->cell(0));
641 params.push_back(optarg);
643 // place cursor in optional argument of macro
645 && thisPos >= int(pos) && thisPos <= int(right)) {
646 int paramPos = std::max(0, thisPos - int(pos) - 1);
647 std::vector<CursorSlice> x;
648 cur.cutOff(thisSlice, x);
649 cur[thisSlice].pos() = macroPos;
651 paramPos = x[0].pos();
654 cur.append(0, paramPos);
660 // fill up empty optional parameters
661 while (params.size() < numOptionalParams) {
662 params.push_back(MathData());
667 void MathData::collectParameters(Cursor & cur,
668 const size_type numParams, std::vector<MathData> & params,
669 size_t & pos, MathAtom & scriptToPutAround,
670 const pos_type macroPos, const int thisPos, const int thisSlice)
672 // insert normal arguments
673 for (; params.size() < numParams && pos < size();) {
674 MathAtom & cell = operator[](pos);
677 std::vector<CursorSlice> argSlices;
679 if (thisSlice != -1 && thisPos == int(pos)) {
680 cur.cutOff(thisSlice, argSlices);
683 // which kind of parameter is it? In {}? With index x^n?
684 InsetMathBrace const * brace = cell->asBraceInset();
686 // found brace, convert into argument
687 params.push_back(brace->cell(0));
689 // cursor inside of the brace or just in front of?
690 if (thisPos == int(pos) && !argSlices.empty()) {
691 argPos = argSlices[0].pos();
692 argSlices.erase(argSlices.begin());
694 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
695 // last inset with scripts without braces
696 // -> they belong to the macro, not the argument
697 InsetMathScript * script = cell.nucleus()->asScriptInset();
698 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
699 // nucleus in brace? Unpack!
700 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
702 params.push_back(script->nuc());
704 // script will be put around below
705 scriptToPutAround = cell;
707 // this should only happen after loading, so make cursor handling simple
708 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
713 // the simplest case: plain inset
715 array.insert(0, cell);
716 params.push_back(array);
719 // put cursor in argument again
720 if (thisSlice != - 1 && thisPos == int(pos)) {
721 cur.append(params.size() - 1, argPos);
722 cur.append(argSlices);
723 cur[thisSlice].pos() = macroPos;
731 int MathData::pos2x(size_type pos) const
733 return pos2x(pos, 0);
737 int MathData::pos2x(size_type pos, int glue) const
740 size_type target = min(pos, size());
741 for (size_type i = 0; i < target; ++i) {
742 const_iterator it = begin() + i;
743 if ((*it)->getChar() == ' ')
745 //lyxerr << "char: " << (*it)->getChar()
746 // << "width: " << (*it)->width() << std::endl;
747 x += atom_dims_[i].wid;
753 MathData::size_type MathData::x2pos(int targetx) const
755 return x2pos(targetx, 0);
759 MathData::size_type MathData::x2pos(int targetx, int glue) const
761 const_iterator it = begin();
764 // find first position after targetx
765 for (; currx < targetx && it < end(); ++it) {
767 if ((*it)->getChar() == ' ')
769 currx += atom_dims_[it - begin()].wid;
773 * If we are not at the beginning of the array, go to the left
774 * of the inset if one of the following two condition holds:
775 * - the current inset is editable (so that the cursor tip is
776 * deeper than us): in this case, we want all intermediate
777 * cursor slices to be before insets;
778 * - the mouse is closer to the left side of the inset than to
780 * See bug 1918 for details.
782 if (it != begin() && currx >= targetx
783 && ((*boost::prior(it))->asNestInset()
784 || abs(lastx - targetx) < abs(currx - targetx))) {
792 int MathData::dist(BufferView const & bv, int x, int y) const
794 return bv.coordCache().getArrays().squareDistance(this, x, y);
798 void MathData::setXY(BufferView & bv, int x, int y) const
800 //lyxerr << "setting position cache for MathData " << this << std::endl;
801 bv.coordCache().arrays().add(this, x, y);
805 Dimension const & MathData::dimension(BufferView const & bv) const
807 return bv.coordCache().getArrays().dim(this);
811 int MathData::xm(BufferView const & bv) const
813 Geometry const & g = bv.coordCache().getArrays().geometry(this);
815 return g.pos.x_ + g.dim.wid / 2;
819 int MathData::ym(BufferView const & bv) const
821 Geometry const & g = bv.coordCache().getArrays().geometry(this);
823 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
827 int MathData::xo(BufferView const & bv) const
829 return bv.coordCache().getArrays().x(this);
833 int MathData::yo(BufferView const & bv) const
835 return bv.coordCache().getArrays().y(this);
839 std::ostream & operator<<(std::ostream & os, MathData const & ar)
841 odocstringstream oss;
842 NormalStream ns(oss);
844 return os << to_utf8(oss.str());
848 odocstream & operator<<(odocstream & os, MathData const & ar)