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);
256 CoordCacheBase<Inset> & coords = mi.base.bv->coordCache().insets();
257 for (size_t i = 0, n = size(); i != n; ++i) {
258 MathAtom const & at = operator[](i);
260 coords.add(at.nucleus(), d);
263 kerning_ = at->kerning(mi.base.bv);
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 CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
291 for (size_t i = 0, n = size(); i != n; ++i) {
292 MathAtom const & at = operator[](i);
293 coords.add(at.nucleus(), x, y);
294 at->drawSelection(pi, x, y);
296 x += coords.dim(at.nucleus()).wid;
301 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
305 for (const_iterator it = begin(); it != end(); ++it) {
306 (*it)->metricsT(mi, d);
312 void MathData::drawT(TextPainter & pain, int x, int y) const
314 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
316 // FIXME: Abdel 16/10/2006
317 // This drawT() method is never used, this is dead code.
319 for (const_iterator it = begin(), et = end(); it != et; ++it) {
320 (*it)->drawT(pain, x, y);
321 //x += (*it)->width_;
327 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
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(mc);
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();
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)) {
356 detachMacroParameters(cur, i);
359 // the macro could have been copied while resizing this
360 macroInset = operator[](i).nucleus()->asMacro();
363 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
364 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
365 // put cursor in front of macro
367 int macroSlice = cur->find(macroInset);
368 if (macroSlice != -1)
369 cur->cutOff(macroSlice - 1);
373 // update the display mode
374 macroInset->setDisplayMode(newDisplayMode);
377 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
378 && (macroInset->arity() != macroNumArgs
379 || macroInset->optionals() != macroOptionals)) {
380 // is it a virgin macro which was never attached to parameters?
381 bool fromInitToNormalMode
382 = (oldDisplayMode == MathMacro::DISPLAY_INIT
383 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
384 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
386 // if the macro was entered interactively (i.e. not by paste or during
387 // loading), it should not be greedy, but the cursor should
388 // automatically jump into the macro when behind
389 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
392 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
393 fromInitToNormalMode, interactive);
396 // FIXME: proper anchor handling, this removes the selection
397 cur->updateInsets(&cur->bottom().inset());
398 cur->clearSelection();
402 // Give macro the chance to adapt to new situation.
403 // The macroInset could be invalid now because it was put into a script
404 // inset and therefore "deep" copied. So get it again from the MathData.
405 InsetMath * inset = operator[](i).nucleus();
406 if (inset->asScriptInset())
407 inset = inset->asScriptInset()->nuc()[0].nucleus();
408 BOOST_ASSERT(inset->asMacro());
409 inset->asMacro()->updateRepresentation(cur);
414 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
416 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
418 // detach all arguments
419 vector<MathData> detachedArgs;
420 if (macroPos + 1 == size())
421 // strip arguments if we are at the MathData end
422 macroInset->detachArguments(detachedArgs, true);
424 macroInset->detachArguments(detachedArgs, false);
427 int curMacroSlice = -1;
429 curMacroSlice = cur->find(macroInset);
430 idx_type curMacroIdx = -1;
431 pos_type curMacroPos = -1;
432 vector<CursorSlice> argSlices;
433 if (curMacroSlice != -1) {
434 curMacroPos = (*cur)[curMacroSlice].pos();
435 curMacroIdx = (*cur)[curMacroSlice].idx();
436 cur->cutOff(curMacroSlice, argSlices);
440 // only [] after the last non-empty argument can be dropped later
441 size_t lastNonEmptyOptional = 0;
442 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
443 if (!detachedArgs[l].empty())
444 lastNonEmptyOptional = l;
447 // optional arguments to be put back?
448 pos_type p = macroPos + 1;
450 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
451 // another non-empty parameter follows?
452 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
454 // then we can drop empty optional parameters
455 if (detachedArgs[j].empty() && canDropEmptyOptional) {
456 if (curMacroIdx == j)
457 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
461 // Otherwise we don't drop an empty optional, put it back normally
463 asArray(from_ascii("[]"), optarg);
464 MathData & arg = detachedArgs[j];
466 // look for "]", i.e. put a brace around?
467 InsetMathBrace * brace = 0;
468 for (size_t q = 0; q < arg.size(); ++q) {
469 if (arg[q]->getChar() == ']') {
471 brace = new InsetMathBrace();
476 // put arg between []
478 brace->cell(0) = arg;
479 optarg.insert(1, MathAtom(brace));
481 optarg.insert(1, arg);
483 // insert it into the array
488 if (curMacroSlice == -1)
491 // cursor in optional argument of macro?
492 if (curMacroIdx == j) {
494 cur->append(0, curMacroPos);
495 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
497 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
498 cur->append(argSlices);
499 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
500 // cursor right of macro
501 (*cur)[curMacroSlice - 1].pos() += optarg.size();
504 // put them back into the MathData
505 for (; j < detachedArgs.size(); ++j, ++p) {
506 MathData const & arg = detachedArgs[j];
508 && !arg[0]->asScriptInset()
509 && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
512 insert(p, MathAtom(new InsetMathBrace(arg)));
515 if (curMacroSlice == -1)
518 // cursor in j-th argument of macro?
519 if (curMacroIdx == j) {
520 if (operator[](p).nucleus()->asBraceInset()) {
521 (*cur)[curMacroSlice - 1].pos() = p;
522 cur->append(0, curMacroPos);
523 cur->append(argSlices);
525 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
526 cur->append(argSlices);
528 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
529 ++(*cur)[curMacroSlice - 1].pos();
533 // FIXME: proper anchor handling, this removes the selection
534 cur->clearSelection();
535 cur->updateInsets(&cur->bottom().inset());
540 void MathData::attachMacroParameters(Cursor * cur,
541 const size_type macroPos, const size_type macroNumArgs,
542 const int macroOptionals, const bool fromInitToNormalMode,
543 const bool interactiveInit)
545 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
547 // start at atom behind the macro again, maybe with some new arguments
548 // from the detach phase above, to add them back into the macro inset
549 size_t p = macroPos + 1;
550 vector<MathData> detachedArgs;
551 MathAtom scriptToPutAround;
553 // find cursor slice again of this MathData
556 thisSlice = cur->find(*this);
559 thisPos = (*cur)[thisSlice].pos();
561 // find arguments behind the macro
562 if (!interactiveInit) {
563 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
564 scriptToPutAround, macroPos, thisPos, thisSlice);
565 collectParameters(cur, macroNumArgs, detachedArgs, p,
566 scriptToPutAround, macroPos, thisPos, thisSlice);
569 // attach arguments back to macro inset
570 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
572 // found tail script? E.g. \foo{a}b^x
573 if (scriptToPutAround.nucleus()) {
574 // put macro into a script inset
575 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
576 = operator[](macroPos);
577 operator[](macroPos) = scriptToPutAround;
579 // go into the script inset nucleus
580 if (cur && thisPos == int(macroPos))
583 // get pointer to "deep" copied macro inset
584 InsetMathScript * scriptInset
585 = operator[](macroPos).nucleus()->asScriptInset();
586 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
589 // remove them from the MathData
590 erase(begin() + macroPos + 1, begin() + p);
592 // cursor outside this MathData?
596 // fix cursor if right of p
597 if (thisPos >= int(p))
598 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
600 // was the macro inset just inserted interactively and was now folded
601 // and the cursor is just behind?
602 if ((*cur)[thisSlice].pos() == int(macroPos + 1)
604 && fromInitToNormalMode
605 && macroInset->arity() > 0
606 && thisSlice + 1 == int(cur->depth())) {
607 // then enter it if the cursor was just behind
608 (*cur)[thisSlice].pos() = macroPos;
609 cur->push_back(CursorSlice(*macroInset));
610 macroInset->idxFirst(*cur);
615 void MathData::collectOptionalParameters(Cursor * cur,
616 const size_type numOptionalParams, vector<MathData> & params,
617 size_t & pos, MathAtom & scriptToPutAround,
618 const pos_type macroPos, const int thisPos, const int thisSlice)
620 // insert optional arguments?
621 while (params.size() < numOptionalParams
623 && !scriptToPutAround.nucleus()) {
624 // is a [] block following which could be an optional parameter?
625 if (operator[](pos)->getChar() != '[')
628 // found possible optional argument, look for "]"
629 size_t right = pos + 1;
630 for (; right < size(); ++right) {
631 MathAtom & cell = operator[](right);
633 if (cell->getChar() == ']')
637 // maybe "]" with a script around?
638 InsetMathScript * script = cell.nucleus()->asScriptInset();
641 if (script->nuc().size() != 1)
643 if (script->nuc()[0]->getChar() == ']') {
644 // script will be put around the macro later
645 scriptToPutAround = cell;
651 if (right >= size()) {
652 // no ] found, so it's not an optional argument
656 // add everything between [ and ] as optional argument
657 MathData optarg(begin() + pos + 1, begin() + right);
661 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
663 params.push_back(optarg[0]->asBraceInset()->cell(0));
665 params.push_back(optarg);
667 // place cursor in optional argument of macro
669 && thisPos >= int(pos) && thisPos <= int(right)) {
670 int paramPos = max(0, thisPos - int(pos) - 1);
671 vector<CursorSlice> x;
672 cur->cutOff(thisSlice, x);
673 (*cur)[thisSlice].pos() = macroPos;
675 paramPos = x[0].pos();
678 cur->append(0, paramPos);
684 // fill up empty optional parameters
685 while (params.size() < numOptionalParams)
686 params.push_back(MathData());
690 void MathData::collectParameters(Cursor * cur,
691 const size_type numParams, vector<MathData> & params,
692 size_t & pos, MathAtom & scriptToPutAround,
693 const pos_type macroPos, const int thisPos, const int thisSlice)
695 // insert normal arguments
696 while (params.size() < numParams
698 && !scriptToPutAround.nucleus()) {
699 MathAtom & cell = operator[](pos);
702 vector<CursorSlice> argSlices;
704 if (thisSlice != -1 && thisPos == int(pos))
705 cur->cutOff(thisSlice, argSlices);
707 // which kind of parameter is it? In {}? With index x^n?
708 InsetMathBrace const * brace = cell->asBraceInset();
710 // found brace, convert into argument
711 params.push_back(brace->cell(0));
713 // cursor inside of the brace or just in front of?
714 if (thisPos == int(pos) && !argSlices.empty()) {
715 argPos = argSlices[0].pos();
716 argSlices.erase(argSlices.begin());
718 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
719 // last inset with scripts without braces
720 // -> they belong to the macro, not the argument
721 InsetMathScript * script = cell.nucleus()->asScriptInset();
722 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
723 // nucleus in brace? Unpack!
724 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
726 params.push_back(script->nuc());
728 // script will be put around below
729 scriptToPutAround = cell;
731 // this should only happen after loading, so make cursor handling simple
732 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
738 // the simplest case: plain inset
740 array.insert(0, cell);
741 params.push_back(array);
744 // put cursor in argument again
745 if (thisSlice != - 1 && thisPos == int(pos)) {
746 cur->append(params.size() - 1, argPos);
747 cur->append(argSlices);
748 (*cur)[thisSlice].pos() = macroPos;
756 int MathData::pos2x(BufferView const * bv, size_type pos) const
758 return pos2x(bv, pos, 0);
762 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
765 size_type target = min(pos, size());
766 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
767 for (size_type i = 0; i < target; ++i) {
768 const_iterator it = begin() + i;
769 if ((*it)->getChar() == ' ')
771 //lyxerr << "char: " << (*it)->getChar()
772 // << "width: " << (*it)->width() << endl;
773 x += coords.dim((*it).nucleus()).wid;
779 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
781 return x2pos(bv, targetx, 0);
785 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
787 const_iterator it = begin();
790 CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
791 // find first position after targetx
792 for (; currx < targetx && it < end(); ++it) {
794 if ((*it)->getChar() == ' ')
796 currx += coords.dim((*it).nucleus()).wid;
800 * If we are not at the beginning of the array, go to the left
801 * of the inset if one of the following two condition holds:
802 * - the current inset is editable (so that the cursor tip is
803 * deeper than us): in this case, we want all intermediate
804 * cursor slices to be before insets;
805 * - the mouse is closer to the left side of the inset than to
807 * See bug 1918 for details.
809 if (it != begin() && currx >= targetx
810 && ((*boost::prior(it))->asNestInset()
811 || abs(lastx - targetx) < abs(currx - targetx))) {
819 int MathData::dist(BufferView const & bv, int x, int y) const
821 return bv.coordCache().getArrays().squareDistance(this, x, y);
825 void MathData::setXY(BufferView & bv, int x, int y) const
827 //lyxerr << "setting position cache for MathData " << this << endl;
828 bv.coordCache().arrays().add(this, x, y);
832 Dimension const & MathData::dimension(BufferView const & bv) const
834 return bv.coordCache().getArrays().dim(this);
838 int MathData::xm(BufferView const & bv) const
840 Geometry const & g = bv.coordCache().getArrays().geometry(this);
842 return g.pos.x_ + g.dim.wid / 2;
846 int MathData::ym(BufferView const & bv) const
848 Geometry const & g = bv.coordCache().getArrays().geometry(this);
850 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
854 int MathData::xo(BufferView const & bv) const
856 return bv.coordCache().getArrays().x(this);
860 int MathData::yo(BufferView const & bv) const
862 return bv.coordCache().getArrays().y(this);
866 ostream & operator<<(ostream & os, MathData const & ar)
868 odocstringstream oss;
869 NormalStream ns(oss);
871 return os << to_utf8(oss.str());
875 odocstream & operator<<(odocstream & os, MathData const & ar)