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 Cursor & cur = mi.base.bv->cursor();
251 const_cast<MathData*>(this)->updateMacros(&cur, mi.macrocontext);
257 for (size_t i = 0, n = size(); i != n; ++i) {
258 MathAtom const & at = operator[](i);
260 atom_dims_.push_back(d);
263 kerning_ = at->kerning();
265 // Cache the dimension.
266 mi.base.bv->coordCache().arrays().add(this, dim);
270 void MathData::draw(PainterInfo & pi, int x, int y) const
272 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
273 BufferView & bv = *pi.base.bv;
276 Dimension const & dim = bv.coordCache().getArrays().dim(this);
279 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
283 // don't draw outside the workarea
284 if (y + dim.descent() <= 0
285 || y - dim.ascent() >= bv.workHeight()
286 || x + dim.width() <= 0
287 || x >= bv. workWidth())
290 for (size_t i = 0, n = size(); i != n; ++i) {
291 MathAtom const & at = operator[](i);
292 bv.coordCache().insets().add(at.nucleus(), x, y);
293 at->drawSelection(pi, x, y);
295 x += atom_dims_[i].wid;
300 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
304 for (const_iterator it = begin(); it != end(); ++it) {
305 (*it)->metricsT(mi, d);
311 void MathData::drawT(TextPainter & pain, int x, int y) const
313 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
315 // FIXME: Abdel 16/10/2006
316 // This drawT() method is never used, this is dead code.
318 for (const_iterator it = begin(), et = end(); it != et; ++it) {
319 (*it)->drawT(pain, x, y);
320 //x += (*it)->width_;
326 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
328 // go over the array and look for macros
329 for (size_t i = 0; i < size(); ++i) {
330 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
335 macroInset->updateMacro(mc);
336 size_t macroNumArgs = 0;
337 size_t macroOptionals = 0;
338 MacroData const * macro = macroInset->macro();
340 macroNumArgs = macro->numargs();
341 macroOptionals = macro->optionals();
344 // store old and compute new display mode
345 MathMacro::DisplayMode newDisplayMode;
346 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
347 newDisplayMode = macroInset->computeDisplayMode();
349 // arity changed or other reason to detach?
350 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
351 && (macroInset->arity() != macroNumArgs
352 || macroInset->optionals() != macroOptionals
353 || 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
366 int macroSlice = cur->find(macroInset);
367 if (macroSlice != -1)
368 cur->cutOff(macroSlice - 1);
372 // update the display mode
373 macroInset->setDisplayMode(newDisplayMode);
376 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
377 && (macroInset->arity() != macroNumArgs
378 || macroInset->optionals() != macroOptionals)) {
379 // is it a virgin macro which was never attached to parameters?
380 bool fromInitToNormalMode
381 = (oldDisplayMode == MathMacro::DISPLAY_INIT
382 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
383 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
385 // if the macro was entered interactively (i.e. not by paste or during
386 // loading), it should not be greedy, but the cursor should
387 // automatically jump into the macro when behind
388 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
391 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
392 fromInitToNormalMode, interactive);
395 // FIXME: proper anchor handling, this removes the selection
396 cur->updateInsets(&cur->bottom().inset());
397 cur->clearSelection();
401 // Give macro the chance to adapt to new situation.
402 // The macroInset could be invalid now because it was put into a script
403 // inset and therefore "deep" copied. So get it again from the MathData.
404 InsetMath * inset = operator[](i).nucleus();
405 if (inset->asScriptInset())
406 inset = inset->asScriptInset()->nuc()[0].nucleus();
407 BOOST_ASSERT(inset->asMacro());
408 inset->asMacro()->updateRepresentation(cur);
413 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
415 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
417 // detach all arguments
418 vector<MathData> detachedArgs;
419 if (macroPos + 1 == size())
420 // strip arguments if we are at the MathData end
421 macroInset->detachArguments(detachedArgs, true);
423 macroInset->detachArguments(detachedArgs, false);
426 int curMacroSlice = -1;
428 curMacroSlice = cur->find(macroInset);
429 idx_type curMacroIdx = -1;
430 pos_type curMacroPos = -1;
431 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];
507 && !arg[0]->asScriptInset()
508 && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
511 insert(p, MathAtom(new InsetMathBrace(arg)));
514 if (curMacroSlice == -1)
517 // cursor in j-th argument of macro?
518 if (curMacroIdx == j) {
519 if (operator[](p).nucleus()->asBraceInset()) {
520 (*cur)[curMacroSlice - 1].pos() = p;
521 cur->append(0, curMacroPos);
522 cur->append(argSlices);
524 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
525 cur->append(argSlices);
527 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
528 ++(*cur)[curMacroSlice - 1].pos();
532 // FIXME: proper anchor handling, this removes the selection
533 cur->clearSelection();
534 cur->updateInsets(&cur->bottom().inset());
539 void MathData::attachMacroParameters(Cursor * cur,
540 const size_type macroPos, const size_type macroNumArgs,
541 const int macroOptionals, const bool fromInitToNormalMode,
542 const bool interactiveInit)
544 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
546 // start at atom behind the macro again, maybe with some new arguments
547 // from the detach phase above, to add them back into the macro inset
548 size_t p = macroPos + 1;
549 vector<MathData> detachedArgs;
550 MathAtom scriptToPutAround;
552 // find cursor slice again of this MathData
555 thisSlice = cur->find(*this);
558 thisPos = (*cur)[thisSlice].pos();
560 // find arguments behind the macro
561 if (!interactiveInit) {
562 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
563 macroPos, thisPos, thisSlice);
564 collectParameters(cur, macroNumArgs, detachedArgs, p,
565 scriptToPutAround, macroPos, thisPos, thisSlice);
568 // attach arguments back to macro inset
569 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
571 // found tail script? E.g. \foo{a}b^x
572 if (scriptToPutAround.nucleus()) {
573 // put macro into a script inset
574 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
575 = operator[](macroPos);
576 operator[](macroPos) = scriptToPutAround;
578 // go into the script inset nucleus
579 if (cur && thisPos == int(macroPos))
582 // get pointer to "deep" copied macro inset
583 InsetMathScript * scriptInset
584 = operator[](macroPos).nucleus()->asScriptInset();
585 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
588 // remove them from the MathData
589 erase(begin() + macroPos + 1, begin() + p);
591 // cursor outside this MathData?
595 // fix cursor if right of p
596 if (thisPos >= int(p))
597 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
599 // was the macro inset just inserted interactively and was now folded
600 // and the cursor is just behind?
601 if ((*cur)[thisSlice].pos() == int(macroPos + 1)
603 && fromInitToNormalMode
604 && macroInset->arity() > 0
605 && thisSlice + 1 == int(cur->depth())) {
606 // then enter it if the cursor was just behind
607 (*cur)[thisSlice].pos() = macroPos;
608 cur->push_back(CursorSlice(*macroInset));
609 macroInset->idxFirst(*cur);
614 void MathData::collectOptionalParameters(Cursor * cur,
615 const size_type numOptionalParams, vector<MathData> & params,
616 size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
618 // insert optional arguments?
619 while (params.size() < numOptionalParams && pos < size()) {
620 // is a [] block following which could be an optional parameter?
621 if (operator[](pos)->getChar() != '[')
624 // found possible optional argument, look for "]"
625 size_t right = pos + 1;
626 for (; right < size(); ++right) {
627 if (operator[](right)->getChar() == ']')
633 if (right >= size()) {
634 // no ] found, so it's not an optional argument
638 // add everything between [ and ] as optional argument
639 MathData optarg(begin() + pos + 1, begin() + right);
643 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
645 params.push_back(optarg[0]->asBraceInset()->cell(0));
647 params.push_back(optarg);
649 // place cursor in optional argument of macro
651 && thisPos >= int(pos) && thisPos <= int(right)) {
652 int paramPos = max(0, thisPos - int(pos) - 1);
653 vector<CursorSlice> x;
654 cur->cutOff(thisSlice, x);
655 (*cur)[thisSlice].pos() = macroPos;
657 paramPos = x[0].pos();
660 cur->append(0, paramPos);
666 // fill up empty optional parameters
667 while (params.size() < numOptionalParams)
668 params.push_back(MathData());
672 void MathData::collectParameters(Cursor * cur,
673 const size_type numParams, vector<MathData> & params,
674 size_t & pos, MathAtom & scriptToPutAround,
675 const pos_type macroPos, const int thisPos, const int thisSlice)
677 // insert normal arguments
678 for (; params.size() < numParams && pos < size();) {
679 MathAtom & cell = operator[](pos);
682 vector<CursorSlice> argSlices;
684 if (thisSlice != -1 && thisPos == int(pos))
685 cur->cutOff(thisSlice, argSlices);
687 // which kind of parameter is it? In {}? With index x^n?
688 InsetMathBrace const * brace = cell->asBraceInset();
690 // found brace, convert into argument
691 params.push_back(brace->cell(0));
693 // cursor inside of the brace or just in front of?
694 if (thisPos == int(pos) && !argSlices.empty()) {
695 argPos = argSlices[0].pos();
696 argSlices.erase(argSlices.begin());
698 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
699 // last inset with scripts without braces
700 // -> they belong to the macro, not the argument
701 InsetMathScript * script = cell.nucleus()->asScriptInset();
702 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
703 // nucleus in brace? Unpack!
704 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
706 params.push_back(script->nuc());
708 // script will be put around below
709 scriptToPutAround = cell;
711 // this should only happen after loading, so make cursor handling simple
712 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
718 // the simplest case: plain inset
720 array.insert(0, cell);
721 params.push_back(array);
724 // put cursor in argument again
725 if (thisSlice != - 1 && thisPos == int(pos)) {
726 cur->append(params.size() - 1, argPos);
727 cur->append(argSlices);
728 (*cur)[thisSlice].pos() = macroPos;
736 int MathData::pos2x(size_type pos) const
738 return pos2x(pos, 0);
742 int MathData::pos2x(size_type pos, int glue) const
745 size_type target = min(pos, size());
746 for (size_type i = 0; i < target; ++i) {
747 const_iterator it = begin() + i;
748 if ((*it)->getChar() == ' ')
750 //lyxerr << "char: " << (*it)->getChar()
751 // << "width: " << (*it)->width() << endl;
752 x += atom_dims_[i].wid;
758 MathData::size_type MathData::x2pos(int targetx) const
760 return x2pos(targetx, 0);
764 MathData::size_type MathData::x2pos(int targetx, int glue) const
766 const_iterator it = begin();
769 // find first position after targetx
770 for (; currx < targetx && it < end(); ++it) {
772 if ((*it)->getChar() == ' ')
774 currx += atom_dims_[it - begin()].wid;
778 * If we are not at the beginning of the array, go to the left
779 * of the inset if one of the following two condition holds:
780 * - the current inset is editable (so that the cursor tip is
781 * deeper than us): in this case, we want all intermediate
782 * cursor slices to be before insets;
783 * - the mouse is closer to the left side of the inset than to
785 * See bug 1918 for details.
787 if (it != begin() && currx >= targetx
788 && ((*boost::prior(it))->asNestInset()
789 || abs(lastx - targetx) < abs(currx - targetx))) {
797 int MathData::dist(BufferView const & bv, int x, int y) const
799 return bv.coordCache().getArrays().squareDistance(this, x, y);
803 void MathData::setXY(BufferView & bv, int x, int y) const
805 //lyxerr << "setting position cache for MathData " << this << endl;
806 bv.coordCache().arrays().add(this, x, y);
810 Dimension const & MathData::dimension(BufferView const & bv) const
812 return bv.coordCache().getArrays().dim(this);
816 int MathData::xm(BufferView const & bv) const
818 Geometry const & g = bv.coordCache().getArrays().geometry(this);
820 return g.pos.x_ + g.dim.wid / 2;
824 int MathData::ym(BufferView const & bv) const
826 Geometry const & g = bv.coordCache().getArrays().geometry(this);
828 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
832 int MathData::xo(BufferView const & bv) const
834 return bv.coordCache().getArrays().x(this);
838 int MathData::yo(BufferView const & bv) const
840 return bv.coordCache().getArrays().y(this);
844 ostream & operator<<(ostream & os, MathData const & ar)
846 odocstringstream oss;
847 NormalStream ns(oss);
849 return os << to_utf8(oss.str());
853 odocstream & operator<<(odocstream & os, MathData const & ar)