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"
30 #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>
45 MathData::MathData(const_iterator from, const_iterator to)
50 MathAtom & MathData::operator[](pos_type pos)
52 BOOST_ASSERT(pos < size());
53 return base_type::operator[](pos);
57 MathAtom const & MathData::operator[](pos_type pos) const
59 BOOST_ASSERT(pos < size());
60 return base_type::operator[](pos);
64 void MathData::insert(size_type pos, MathAtom const & t)
66 base_type::insert(begin() + pos, t);
70 void MathData::insert(size_type pos, MathData const & ar)
72 BOOST_ASSERT(pos <= size());
73 base_type::insert(begin() + pos, ar.begin(), ar.end());
77 void MathData::append(MathData const & ar)
83 void MathData::erase(size_type pos)
90 void MathData::erase(iterator pos1, iterator pos2)
92 base_type::erase(pos1, pos2);
96 void MathData::erase(iterator pos)
98 base_type::erase(pos);
102 void MathData::erase(size_type pos1, size_type pos2)
104 base_type::erase(begin() + pos1, begin() + pos2);
108 void MathData::dump2() const
112 for (const_iterator it = begin(); it != end(); ++it)
114 lyxerr << to_utf8(os.str());
118 void MathData::dump() const
122 for (const_iterator it = begin(); it != end(); ++it)
123 ns << '<' << *it << '>';
124 lyxerr << to_utf8(os.str());
128 void MathData::validate(LaTeXFeatures & features) const
130 for (const_iterator it = begin(); it != end(); ++it)
131 (*it)->validate(features);
135 bool MathData::match(MathData const & ar) const
137 return size() == ar.size() && matchpart(ar, 0);
141 bool MathData::matchpart(MathData const & ar, pos_type pos) const
143 if (size() < ar.size() + pos)
145 const_iterator it = begin() + pos;
146 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
147 if (asString(*it) != asString(*jt))
153 void MathData::replace(ReplaceData & rep)
155 for (size_type i = 0; i < size(); ++i) {
156 if (find1(rep.from, i)) {
158 lyxerr << "match found!" << endl;
159 erase(i, i + rep.from.size());
164 // FIXME: temporarily disabled
165 // for (const_iterator it = begin(); it != end(); ++it)
166 // it->nucleus()->replace(rep);
170 bool MathData::find1(MathData const & ar, size_type pos) const
172 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
173 for (size_type i = 0, n = ar.size(); i < n; ++i)
174 if (asString(operator[](pos + i)) != asString(ar[i]))
180 MathData::size_type MathData::find(MathData const & ar) const
182 for (int i = 0, last = size() - ar.size(); i < last; ++i)
189 MathData::size_type MathData::find_last(MathData const & ar) const
191 for (int i = size() - ar.size(); i >= 0; --i)
198 bool MathData::contains(MathData const & ar) const
200 if (find(ar) != size())
202 for (const_iterator it = begin(); it != end(); ++it)
203 if ((*it)->contains(ar))
209 void MathData::touch() const
216 bool isInside(DocIterator const & it, MathData const & ar,
217 pos_type p1, pos_type p2)
219 for (size_t i = 0; i != it.depth(); ++i) {
220 CursorSlice const & sl = it[i];
221 if (sl.inset().inMathed() && &sl.cell() == &ar)
222 return p1 <= sl.pos() && sl.pos() < p2;
231 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
233 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
234 dim = fm.dimension('I');
235 int xascent = fm.dimension('x').ascent();
236 if (xascent >= dim.asc)
237 xascent = (2 * dim.asc) / 3;
239 mindes_ = (3 * xascent) / 4;
240 slevel_ = (4 * xascent) / 5;
241 sshift_ = xascent / 4;
245 // Cache the dimension.
246 mi.base.bv->coordCache().arrays().add(this, dim);
250 const_cast<MathData*>(this)->updateMacros(mi);
256 for (size_t i = 0, n = size(); i != n; ++i) {
257 MathAtom const & at = operator[](i);
259 atom_dims_.push_back(d);
262 kerning_ = at->kerning();
264 // Cache the dimension.
265 mi.base.bv->coordCache().arrays().add(this, dim);
269 void MathData::draw(PainterInfo & pi, int x, int y) const
271 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
272 BufferView & bv = *pi.base.bv;
275 Dimension const & dim = bv.coordCache().getArrays().dim(this);
278 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
282 // don't draw outside the workarea
283 if (y + dim.descent() <= 0
284 || y - dim.ascent() >= bv.workHeight()
285 || x + dim.width() <= 0
286 || x >= bv. workWidth())
289 for (size_t i = 0, n = size(); i != n; ++i) {
290 MathAtom const & at = operator[](i);
291 bv.coordCache().insets().add(at.nucleus(), x, y);
292 at->drawSelection(pi, x, y);
294 x += atom_dims_[i].wid;
299 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
303 for (const_iterator it = begin(); it != end(); ++it) {
304 (*it)->metricsT(mi, d);
310 void MathData::drawT(TextPainter & pain, int x, int y) const
312 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
314 // FIXME: Abdel 16/10/2006
315 // This drawT() method is never used, this is dead code.
317 for (const_iterator it = begin(), et = end(); it != et; ++it) {
318 (*it)->drawT(pain, x, y);
319 //x += (*it)->width_;
325 void MathData::updateMacros(MetricsInfo & mi)
327 Cursor & cur = mi.base.bv->cursor();
329 // go over the array and look for macros
330 for (size_t i = 0; i < size(); ++i) {
331 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
336 macroInset->updateMacro(mi);
337 size_t macroNumArgs = 0;
338 size_t macroOptionals = 0;
339 MacroData const * macro = macroInset->macro();
341 macroNumArgs = macro->numargs();
342 macroOptionals = macro->optionals();
345 // store old and compute new display mode
346 MathMacro::DisplayMode newDisplayMode;
347 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
348 newDisplayMode = macroInset->computeDisplayMode(mi);
350 // arity changed or other reason to detach?
351 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
352 && (macroInset->arity() != macroNumArgs
353 || macroInset->optionals() != macroOptionals
354 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
355 detachMacroParameters(cur, i);
358 // the macro could have been copied while resizing this
359 macroInset = operator[](i).nucleus()->asMacro();
362 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
363 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
364 // put cursor in front of macro
365 int macroSlice = cur.find(macroInset);
366 if (macroSlice != -1)
367 cur.cutOff(macroSlice - 1);
370 // update the display mode
371 macroInset->setDisplayMode(newDisplayMode);
374 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
375 && (macroInset->arity() != macroNumArgs
376 || macroInset->optionals() != macroOptionals)) {
377 // is it a virgin macro which was never attached to parameters?
378 bool fromInitToNormalMode
379 = (oldDisplayMode == MathMacro::DISPLAY_INIT
380 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
381 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
383 // if the macro was entered interactively (i.e. not by paste or during
384 // loading), it should not be greedy, but the cursor should
385 // automatically jump into the macro when behind
386 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
389 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
390 fromInitToNormalMode, interactive);
392 // FIXME: proper anchor handling, this removes the selection
393 cur.updateInsets(&cur.bottom().inset());
394 cur.clearSelection();
397 // Give macro the chance to adapt to new situation.
398 // The macroInset could be invalid now because it was put into a script
399 // inset and therefore "deep" copied. So get it again from the MathData.
400 InsetMath * inset = operator[](i).nucleus();
401 if (inset->asScriptInset())
402 inset = inset->asScriptInset()->nuc()[0].nucleus();
403 BOOST_ASSERT(inset->asMacro());
404 inset->asMacro()->updateRepresentation(mi);
409 void MathData::detachMacroParameters(Cursor & cur, const size_type macroPos)
411 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
413 // detach all arguments
414 vector<MathData> detachedArgs;
415 if (macroPos + 1 == size())
416 // strip arguments if we are at the MathData end
417 macroInset->detachArguments(detachedArgs, true);
419 macroInset->detachArguments(detachedArgs, false);
422 int curMacroSlice = cur.find(macroInset);
423 idx_type curMacroIdx = -1;
424 pos_type curMacroPos = -1;
425 vector<CursorSlice> argSlices;
426 if (curMacroSlice != -1) {
427 curMacroPos = cur[curMacroSlice].pos();
428 curMacroIdx = cur[curMacroSlice].idx();
429 cur.cutOff(curMacroSlice, argSlices);
433 // only [] after the last non-empty argument can be dropped later
434 size_t lastNonEmptyOptional = 0;
435 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
436 if (!detachedArgs[l].empty())
437 lastNonEmptyOptional = l;
440 // optional arguments to be put back?
441 pos_type p = macroPos + 1;
443 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
444 // another non-empty parameter follows?
445 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
447 // then we can drop empty optional parameters
448 if (detachedArgs[j].empty() && canDropEmptyOptional) {
449 if (curMacroIdx == j)
450 cur[curMacroSlice - 1].pos() = macroPos + 1;
454 // Otherwise we don't drop an empty optional, put it back normally
456 asArray(from_ascii("[]"), optarg);
457 MathData & arg = detachedArgs[j];
459 // look for "]", i.e. put a brace around?
460 InsetMathBrace * brace = 0;
461 for (size_t q = 0; q < arg.size(); ++q) {
462 if (arg[q]->getChar() == ']') {
464 brace = new InsetMathBrace();
469 // put arg between []
471 brace->cell(0) = arg;
472 optarg.insert(1, MathAtom(brace));
474 optarg.insert(1, arg);
476 // insert it into the array
481 if (curMacroSlice == -1)
484 // cursor in optional argument of macro?
485 if (curMacroIdx == j) {
487 cur.append(0, curMacroPos);
488 cur[curMacroSlice - 1].pos() = macroPos + 2;
490 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
491 cur.append(argSlices);
492 } else if (cur[curMacroSlice - 1].pos() >= int(p))
493 // cursor right of macro
494 cur[curMacroSlice - 1].pos() += optarg.size();
497 // put them back into the MathData
498 for (; j < detachedArgs.size(); ++j, ++p) {
499 MathData const & arg = detachedArgs[j];
500 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
503 insert(p, MathAtom(new InsetMathBrace(arg)));
506 if (curMacroSlice == -1)
509 // cursor in j-th argument of macro?
510 if (curMacroIdx == j) {
511 if (operator[](p).nucleus()->asBraceInset()) {
512 cur[curMacroSlice - 1].pos() = p;
513 cur.append(0, curMacroPos);
514 cur.append(argSlices);
516 cur[curMacroSlice - 1].pos() = p; // + macroPos;
517 cur.append(argSlices);
519 } else if (cur[curMacroSlice - 1].pos() >= int(p))
520 ++cur[curMacroSlice - 1].pos();
523 // FIXME: proper anchor handling, this removes the selection
524 cur.clearSelection();
525 cur.updateInsets(&cur.bottom().inset());
529 void MathData::attachMacroParameters(Cursor & cur,
530 const size_type macroPos, const size_type macroNumArgs,
531 const int macroOptionals, const bool fromInitToNormalMode,
532 const bool interactiveInit)
534 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
536 // start at atom behind the macro again, maybe with some new arguments
537 // from the detach phase above, to add them back into the macro inset
538 size_t p = macroPos + 1;
539 vector<MathData> detachedArgs;
540 MathAtom scriptToPutAround;
542 // find cursor slice again of this MathData
543 int thisSlice = cur.find(*this);
546 thisPos = cur[thisSlice].pos();
548 // find arguments behind the macro
549 if (!interactiveInit) {
550 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
551 macroPos, thisPos, thisSlice);
552 collectParameters(cur, macroNumArgs, detachedArgs, p,
553 scriptToPutAround, macroPos, thisPos, thisSlice);
556 // attach arguments back to macro inset
557 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
559 // found tail script? E.g. \foo{a}b^x
560 if (scriptToPutAround.nucleus()) {
561 // put macro into a script inset
562 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
563 = operator[](macroPos);
564 operator[](macroPos) = scriptToPutAround;
566 // go into the script inset nucleus
567 if (thisPos == int(macroPos))
570 // get pointer to "deep" copied macro inset
571 InsetMathScript * scriptInset
572 = operator[](macroPos).nucleus()->asScriptInset();
573 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
576 // remove them from the MathData
577 erase(begin() + macroPos + 1, begin() + p);
579 // cursor outside this MathData?
583 // fix cursor if right of p
584 if (thisPos >= int(p))
585 cur[thisSlice].pos() -= p - (macroPos + 1);
587 // was the macro inset just inserted interactively and was now folded
588 // and the cursor is just behind?
589 if (cur[thisSlice].pos() == int(macroPos + 1)
591 && fromInitToNormalMode
592 && macroInset->arity() > 0
593 && thisSlice + 1 == int(cur.depth())) {
594 // then enter it if the cursor was just behind
595 cur[thisSlice].pos() = macroPos;
596 cur.push_back(CursorSlice(*macroInset));
597 macroInset->idxFirst(cur);
602 void MathData::collectOptionalParameters(Cursor & cur,
603 const size_type numOptionalParams, vector<MathData> & params,
604 size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
606 // insert optional arguments?
607 while (params.size() < numOptionalParams && pos < size()) {
608 // is a [] block following which could be an optional parameter?
609 if (operator[](pos)->getChar() != '[')
612 // found possible optional argument, look for "]"
613 size_t right = pos + 1;
614 for (; right < size(); ++right) {
615 if (operator[](right)->getChar() == ']')
621 if (right >= size()) {
622 // no ] found, so it's not an optional argument
626 // add everything between [ and ] as optional argument
627 MathData optarg(begin() + pos + 1, begin() + right);
631 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
633 params.push_back(optarg[0]->asBraceInset()->cell(0));
635 params.push_back(optarg);
637 // place cursor in optional argument of macro
639 && thisPos >= int(pos) && thisPos <= int(right)) {
640 int paramPos = max(0, thisPos - int(pos) - 1);
641 vector<CursorSlice> x;
642 cur.cutOff(thisSlice, x);
643 cur[thisSlice].pos() = macroPos;
645 paramPos = x[0].pos();
648 cur.append(0, paramPos);
654 // fill up empty optional parameters
655 while (params.size() < numOptionalParams) {
656 params.push_back(MathData());
661 void MathData::collectParameters(Cursor & cur,
662 const size_type numParams, vector<MathData> & params,
663 size_t & pos, MathAtom & scriptToPutAround,
664 const pos_type macroPos, const int thisPos, const int thisSlice)
666 // insert normal arguments
667 for (; params.size() < numParams && pos < size();) {
668 MathAtom & cell = operator[](pos);
671 vector<CursorSlice> argSlices;
673 if (thisSlice != -1 && thisPos == int(pos)) {
674 cur.cutOff(thisSlice, argSlices);
677 // which kind of parameter is it? In {}? With index x^n?
678 InsetMathBrace const * brace = cell->asBraceInset();
680 // found brace, convert into argument
681 params.push_back(brace->cell(0));
683 // cursor inside of the brace or just in front of?
684 if (thisPos == int(pos) && !argSlices.empty()) {
685 argPos = argSlices[0].pos();
686 argSlices.erase(argSlices.begin());
688 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
689 // last inset with scripts without braces
690 // -> they belong to the macro, not the argument
691 InsetMathScript * script = cell.nucleus()->asScriptInset();
692 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
693 // nucleus in brace? Unpack!
694 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
696 params.push_back(script->nuc());
698 // script will be put around below
699 scriptToPutAround = cell;
701 // this should only happen after loading, so make cursor handling simple
702 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
707 // the simplest case: plain inset
709 array.insert(0, cell);
710 params.push_back(array);
713 // put cursor in argument again
714 if (thisSlice != - 1 && thisPos == int(pos)) {
715 cur.append(params.size() - 1, argPos);
716 cur.append(argSlices);
717 cur[thisSlice].pos() = macroPos;
725 int MathData::pos2x(size_type pos) const
727 return pos2x(pos, 0);
731 int MathData::pos2x(size_type pos, int glue) const
734 size_type target = min(pos, size());
735 for (size_type i = 0; i < target; ++i) {
736 const_iterator it = begin() + i;
737 if ((*it)->getChar() == ' ')
739 //lyxerr << "char: " << (*it)->getChar()
740 // << "width: " << (*it)->width() << endl;
741 x += atom_dims_[i].wid;
747 MathData::size_type MathData::x2pos(int targetx) const
749 return x2pos(targetx, 0);
753 MathData::size_type MathData::x2pos(int targetx, int glue) const
755 const_iterator it = begin();
758 // find first position after targetx
759 for (; currx < targetx && it < end(); ++it) {
761 if ((*it)->getChar() == ' ')
763 currx += atom_dims_[it - begin()].wid;
767 * If we are not at the beginning of the array, go to the left
768 * of the inset if one of the following two condition holds:
769 * - the current inset is editable (so that the cursor tip is
770 * deeper than us): in this case, we want all intermediate
771 * cursor slices to be before insets;
772 * - the mouse is closer to the left side of the inset than to
774 * See bug 1918 for details.
776 if (it != begin() && currx >= targetx
777 && ((*boost::prior(it))->asNestInset()
778 || abs(lastx - targetx) < abs(currx - targetx))) {
786 int MathData::dist(BufferView const & bv, int x, int y) const
788 return bv.coordCache().getArrays().squareDistance(this, x, y);
792 void MathData::setXY(BufferView & bv, int x, int y) const
794 //lyxerr << "setting position cache for MathData " << this << endl;
795 bv.coordCache().arrays().add(this, x, y);
799 Dimension const & MathData::dimension(BufferView const & bv) const
801 return bv.coordCache().getArrays().dim(this);
805 int MathData::xm(BufferView const & bv) const
807 Geometry const & g = bv.coordCache().getArrays().geometry(this);
809 return g.pos.x_ + g.dim.wid / 2;
813 int MathData::ym(BufferView const & bv) const
815 Geometry const & g = bv.coordCache().getArrays().geometry(this);
817 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
821 int MathData::xo(BufferView const & bv) const
823 return bv.coordCache().getArrays().x(this);
827 int MathData::yo(BufferView const & bv) const
829 return bv.coordCache().getArrays().y(this);
833 ostream & operator<<(ostream & os, MathData const & ar)
835 odocstringstream oss;
836 NormalStream ns(oss);
838 return os << to_utf8(oss.str());
842 odocstream & operator<<(odocstream & os, MathData const & ar)