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.
15 #include "InsetMathBrace.h"
16 #include "InsetMathFont.h"
17 #include "InsetMathScript.h"
18 #include "MacroTable.h"
19 #include "MathMacro.h"
20 #include "MathStream.h"
21 #include "MathSupport.h"
22 #include "ReplaceData.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
30 #include "frontends/FontMetrics.h"
31 #include "frontends/Painter.h"
33 #include <boost/assert.hpp>
34 #include <boost/next_prior.hpp>
42 using std::ostringstream;
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 const_cast<MathData*>(this)->updateMacros(mi);
258 for (size_t i = 0, n = size(); i != n; ++i) {
259 MathAtom const & at = operator[](i);
261 atom_dims_.push_back(d);
264 kerning_ = at->kerning();
266 // Cache the dimension.
267 mi.base.bv->coordCache().arrays().add(this, dim);
271 void MathData::draw(PainterInfo & pi, int x, int y) const
273 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
274 BufferView & bv = *pi.base.bv;
277 Dimension const & dim = bv.coordCache().getArrays().dim(this);
280 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
284 // don't draw outside the workarea
285 if (y + dim.descent() <= 0
286 || y - dim.ascent() >= bv.workHeight()
287 || x + dim.width() <= 0
288 || x >= bv. workWidth())
291 for (size_t i = 0, n = size(); i != n; ++i) {
292 MathAtom const & at = operator[](i);
293 bv.coordCache().insets().add(at.nucleus(), x, y);
294 at->drawSelection(pi, x, y);
296 x += atom_dims_[i].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(MetricsInfo & mi)
329 Cursor & cur = mi.base.bv->cursor();
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(mi);
339 size_t macroNumArgs = 0;
340 int 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(mi);
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)) {
357 detachMacroParameters(cur, i);
360 // the macro could have been copied while resizing this
361 macroInset = operator[](i).nucleus()->asMacro();
364 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
365 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
366 // put cursor in front of macro
367 int macroSlice = cur.find(macroInset);
368 if (macroSlice != -1)
369 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_NONGREEDY_INIT)
383 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
384 bool greedy = (oldDisplayMode != MathMacro::DISPLAY_NONGREEDY_INIT);
387 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
388 fromInitToNormalMode, greedy);
390 // FIXME: proper anchor handling, this removes the selection
391 cur.updateInsets(&cur.bottom().inset());
392 cur.clearSelection();
395 // give macro the chance to adapt to new situation
396 InsetMath * inset = operator[](i).nucleus();
397 if (inset->asScriptInset())
398 inset = inset->asScriptInset()->nuc()[0].nucleus();
399 BOOST_ASSERT(inset->asMacro());
400 inset->asMacro()->updateRepresentation(mi);
405 void MathData::detachMacroParameters(Cursor & cur, const size_type macroPos)
407 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
409 // detach all arguments
410 std::vector<MathData> detachedArgs;
411 if (macroPos + 1 == size())
412 // strip arguments if we are at the MathData end
413 macroInset->detachArguments(detachedArgs, true);
415 macroInset->detachArguments(detachedArgs, false);
418 int curMacroSlice = cur.find(macroInset);
419 int curMacroIdx = -1;
420 int curMacroPos = -1;
421 std::vector<CursorSlice> argSlices;
422 if (curMacroSlice != -1) {
423 curMacroPos = cur[curMacroSlice].pos();
424 curMacroIdx = cur[curMacroSlice].idx();
425 cur.cutOff(curMacroSlice, argSlices);
429 // only [] after the last non-empty argument can be dropped later
430 size_t lastNonEmptyOptional = 0;
431 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
432 if (!detachedArgs[l].empty())
433 lastNonEmptyOptional = l;
436 // optional arguments to be put back?
437 size_t p = macroPos + 1;
439 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
440 // another non-empty parameter follows?
441 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
443 // then we can drop empty optional parameters
444 if (detachedArgs[j].empty() && canDropEmptyOptional) {
445 if (curMacroIdx == j)
446 cur[curMacroSlice - 1].pos() = macroPos + 1;
450 // Otherwise we don't drop an empty optional, put it back normally
452 asArray(from_ascii("[]"), optarg);
453 MathData & arg = detachedArgs[j];
455 // look for "]", i.e. put a brace around?
456 InsetMathBrace * brace = 0;
457 for (size_t q = 0; q < arg.size(); ++q) {
458 if (arg[q]->getChar() == ']') {
460 brace = new InsetMathBrace();
465 // put arg between []
467 brace->cell(0) = arg;
468 optarg.insert(1, MathAtom(brace));
470 optarg.insert(1, arg);
472 // insert it into the array
476 // cursor in optional argument of macro?
477 if (curMacroIdx == j) {
479 cur.append(0, curMacroPos);
480 cur[curMacroSlice - 1].pos() = macroPos + 2;
482 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
483 cur.append(argSlices);
484 } else if (cur[curMacroSlice - 1].pos() >= int(p))
485 // cursor right of macro
486 cur[curMacroSlice - 1].pos() += optarg.size();
489 // put them back into the MathData
490 for (; j < detachedArgs.size(); ++j) {
491 MathData const & arg = detachedArgs[j];
492 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
495 insert(p, MathAtom(new InsetMathBrace(arg)));
497 // cursor in j-th argument of macro?
498 if (curMacroIdx == int(j)) {
499 if (operator[](p).nucleus()->asBraceInset()) {
500 cur[curMacroSlice - 1].pos() = p;
501 cur.append(0, curMacroPos);
502 cur.append(argSlices);
504 cur[curMacroSlice - 1].pos() = p; // + macroPos;
505 cur.append(argSlices);
507 } else if (cur[curMacroSlice - 1].pos() >= int(p))
508 ++cur[curMacroSlice - 1].pos();
513 // FIXME: proper anchor handling, this removes the selection
514 cur.clearSelection();
515 cur.updateInsets(&cur.bottom().inset());
519 void MathData::attachMacroParameters(Cursor & cur,
520 const size_type macroPos, const size_type macroNumArgs,
521 const int macroOptionals, const bool fromInitToNormalMode,
524 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
526 // start at atom behind the macro again, maybe with some new arguments from above
527 // to add them back into the macro inset
528 size_t p = macroPos + 1;
529 std::vector<MathData> detachedArgs;
530 MathAtom scriptToPutAround;
532 // find cursor slice again
533 int thisSlice = cur.find(*this);
536 thisPos = cur[thisSlice].pos();
538 // find arguments behind the macro
540 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
541 macroPos, thisPos, thisSlice);
542 collectParameters(cur, macroNumArgs, detachedArgs, p,
544 macroPos, thisPos, thisSlice);
547 // attach arguments back to macro inset
548 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
550 // found tail script? E.g. \foo{a}b^x
551 if (scriptToPutAround.nucleus()) {
552 // put macro into a script inset
553 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
554 = operator[](macroPos);
555 operator[](macroPos) = scriptToPutAround;
557 if (thisPos == int(macroPos))
561 // remove them from the MathData
562 erase(begin() + macroPos + 1, begin() + p);
564 // fix cursor if right of p
565 if (thisPos >= int(p))
566 cur[thisSlice].pos() -= p - (macroPos + 1);
568 // was the macro inset just inserted and was now folded?
569 if (cur[thisSlice].pos() == int(macroPos + 1)
570 && fromInitToNormalMode
571 && macroInset->arity() > 0
572 && thisSlice + 1 == int(cur.depth())) {
573 // then enter it if the cursor was just behind
574 cur[thisSlice].pos() = macroPos;
575 cur.push_back(CursorSlice(*macroInset));
576 macroInset->idxFirst(cur);
581 void MathData::collectOptionalParameters(Cursor & cur,
582 const size_type numOptionalParams, std::vector<MathData> & params,
583 size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
585 // insert optional arguments?
586 while (params.size() < numOptionalParams && pos < size()) {
587 // is a [] block following which could be an optional parameter?
588 if (operator[](pos)->getChar() != '[')
591 // found possible optional argument, look for "]"
592 size_t right = pos + 1;
593 for (; right < size(); ++right) {
594 if (operator[](right)->getChar() == ']')
600 if (right >= size()) {
601 // no ] found, so it's not an optional argument
605 // add everything between [ and ] as optional argument
606 MathData optarg(begin() + pos + 1, begin() + right);
610 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
612 params.push_back(optarg[0]->asBraceInset()->cell(0));
614 params.push_back(optarg);
616 // place cursor in optional argument of macro
617 if (thisPos >= int(pos) && thisPos <= int(right)) {
618 int paramPos = std::max(0, thisPos - int(pos) - 1);
619 std::vector<CursorSlice> x;
620 cur.cutOff(thisSlice, x);
621 cur[thisSlice].pos() = macroPos;
623 paramPos = x[0].pos();
626 cur.append(0, paramPos);
632 // fill up empty optional parameters
633 while (params.size() < numOptionalParams) {
634 params.push_back(MathData());
639 void MathData::collectParameters(Cursor & cur,
640 const size_type numParams, std::vector<MathData> & params,
641 size_t & pos, MathAtom & scriptToPutAround,
642 const pos_type macroPos, const int thisPos, const int thisSlice)
644 // insert normal arguments
645 for (; params.size() < numParams && pos < size();) {
646 MathAtom & cell = operator[](pos);
649 std::vector<CursorSlice> argSlices;
651 if (thisPos == int(pos)) {
652 cur.cutOff(thisSlice, argSlices);
655 // which kind of parameter is it? In {}? With index x^n?
656 InsetMathBrace const * brace = cell->asBraceInset();
658 // found brace, convert into argument
659 params.push_back(brace->cell(0));
661 // cursor inside of the brace or just in front of?
662 if (thisPos == int(pos) && !argSlices.empty()) {
663 argPos = argSlices[0].pos();
664 argSlices.erase(argSlices.begin());
666 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
667 // last inset with scripts without braces
668 // -> they belong to the macro, not the argument
669 InsetMathScript * script = cell.nucleus()->asScriptInset();
670 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
671 // nucleus in brace? Unpack!
672 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
674 params.push_back(script->nuc());
676 // script will be put around below
677 scriptToPutAround = cell;
679 // this should only happen after loading, so make cursor handling simple
680 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
685 // the simplest case: plain inset
687 array.insert(0, cell);
688 params.push_back(array);
691 // put cursor in argument again
692 if (thisPos == int(pos)) {
693 cur.append(params.size() - 1, argPos);
694 cur.append(argSlices);
695 cur[thisSlice].pos() = macroPos;
703 int MathData::pos2x(size_type pos) const
705 return pos2x(pos, 0);
709 int MathData::pos2x(size_type pos, int glue) const
712 size_type target = min(pos, size());
713 for (size_type i = 0; i < target; ++i) {
714 const_iterator it = begin() + i;
715 if ((*it)->getChar() == ' ')
717 //lyxerr << "char: " << (*it)->getChar()
718 // << "width: " << (*it)->width() << std::endl;
719 x += atom_dims_[i].wid;
725 MathData::size_type MathData::x2pos(int targetx) const
727 return x2pos(targetx, 0);
731 MathData::size_type MathData::x2pos(int targetx, int glue) const
733 const_iterator it = begin();
736 // find first position after targetx
737 for (; currx < targetx && it < end(); ++it) {
739 if ((*it)->getChar() == ' ')
741 currx += atom_dims_[it - begin()].wid;
745 * If we are not at the beginning of the array, go to the left
746 * of the inset if one of the following two condition holds:
747 * - the current inset is editable (so that the cursor tip is
748 * deeper than us): in this case, we want all intermediate
749 * cursor slices to be before insets;
750 * - the mouse is closer to the left side of the inset than to
752 * See bug 1918 for details.
754 if (it != begin() && currx >= targetx
755 && ((*boost::prior(it))->asNestInset()
756 || abs(lastx - targetx) < abs(currx - targetx))) {
764 int MathData::dist(BufferView const & bv, int x, int y) const
766 return bv.coordCache().getArrays().squareDistance(this, x, y);
770 void MathData::setXY(BufferView & bv, int x, int y) const
772 //lyxerr << "setting position cache for MathData " << this << std::endl;
773 bv.coordCache().arrays().add(this, x, y);
777 Dimension const & MathData::dimension(BufferView const & bv) const
779 return bv.coordCache().getArrays().dim(this);
783 int MathData::xm(BufferView const & bv) const
785 Geometry const & g = bv.coordCache().getArrays().geometry(this);
787 return g.pos.x_ + g.dim.wid / 2;
791 int MathData::ym(BufferView const & bv) const
793 Geometry const & g = bv.coordCache().getArrays().geometry(this);
795 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
799 int MathData::xo(BufferView const & bv) const
801 return bv.coordCache().getArrays().x(this);
805 int MathData::yo(BufferView const & bv) const
807 return bv.coordCache().getArrays().y(this);
811 std::ostream & operator<<(std::ostream & os, MathData const & ar)
813 odocstringstream oss;
814 NormalStream ns(oss);
816 return os << to_utf8(oss.str());
820 odocstream & operator<<(odocstream & os, MathData const & ar)