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 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
385 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
386 fromInitToNormalMode);
389 // give macro the chance to adapt to new situation
390 InsetMath * inset = operator[](i).nucleus();
391 if (inset->asScriptInset())
392 inset = inset->asScriptInset()->nuc()[0].nucleus();
393 BOOST_ASSERT(inset->asMacro());
394 inset->asMacro()->updateRepresentation(mi);
399 void MathData::detachMacroParameters(Cursor & cur, const size_type macroPos)
401 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
403 // detach all arguments
404 std::vector<MathData> detachedArgs;
405 if (macroPos + 1 == size())
406 // strip arguments if we are at the MathData end
407 macroInset->detachArguments(detachedArgs, true);
409 macroInset->detachArguments(detachedArgs, false);
412 int curMacroSlice = cur.find(macroInset);
413 int curMacroIdx = -1;
414 int curMacroPos = -1;
415 std::vector<CursorSlice> argSlices;
416 if (curMacroSlice != -1) {
417 curMacroPos = cur[curMacroSlice].pos();
418 curMacroIdx = cur[curMacroSlice].idx();
419 cur.cutOff(curMacroSlice, argSlices);
423 // only [] after the last non-empty argument can be dropped later
424 size_t lastNonEmptyOptional = 0;
425 for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
426 if (!detachedArgs[l].empty())
427 lastNonEmptyOptional = l;
430 // optional arguments to be put back?
431 size_t p = macroPos + 1;
433 for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
434 // another non-empty parameter follows?
435 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
437 // then we can drop empty optional parameters
438 if (detachedArgs[j].empty() && canDropEmptyOptional) {
439 if (curMacroIdx == j)
440 cur[curMacroSlice - 1].pos() = macroPos + 1;
444 // Otherwise we don't drop an empty optional, put it back normally
446 asArray(from_ascii("[]"), optarg);
447 MathData & arg = detachedArgs[j];
449 // look for "]", i.e. put a brace around?
450 InsetMathBrace * brace = 0;
451 for (size_t q = 0; q < arg.size(); ++q) {
452 if (arg[q]->getChar() == ']') {
454 brace = new InsetMathBrace();
459 // put arg between []
461 brace->cell(0) = arg;
462 optarg.insert(1, MathAtom(brace));
464 optarg.insert(1, arg);
466 // insert it into the array
470 // cursor in optional argument of macro?
471 if (curMacroIdx == j) {
473 cur.append(0, curMacroPos);
474 cur[curMacroSlice - 1].pos() = macroPos + 2;
476 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
477 cur.append(argSlices);
478 } else if (cur[curMacroSlice - 1].pos() >= int(p))
479 // cursor right of macro
480 cur[curMacroSlice - 1].pos() += optarg.size();
483 // put them back into the MathData
484 for (; j < detachedArgs.size(); ++j) {
485 MathData const & arg = detachedArgs[j];
486 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
489 insert(p, MathAtom(new InsetMathBrace(arg)));
491 // cursor in j-th argument of macro?
492 if (curMacroIdx == int(j)) {
493 if (operator[](p).nucleus()->asBraceInset()) {
494 cur[curMacroSlice - 1].pos() = p;
495 cur.append(0, curMacroPos);
496 cur.append(argSlices);
498 cur[curMacroSlice - 1].pos() = p; // + macroPos;
499 cur.append(argSlices);
501 } else if (cur[curMacroSlice - 1].pos() >= int(p))
502 ++cur[curMacroSlice - 1].pos();
507 // FIXME: proper anchor handling, this removes the selection
508 cur.clearSelection();
509 cur.updateInsets(&cur.bottom().inset());
513 void MathData::attachMacroParameters(Cursor & cur,
514 const size_type macroPos, const size_type macroNumArgs,
515 const int macroOptionals, const bool fromInitToNormalMode)
517 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
519 // start at atom behind the macro again, maybe with some new arguments from above
520 // to add them back into the macro inset
521 size_t p = macroPos + 1;
523 std::vector<MathData>detachedArgs;
524 MathAtom scriptToPutAround;
526 // find cursor slice again
527 int thisSlice = cur.find(*this);
530 thisPos = cur[thisSlice].pos();
532 // insert optional arguments?
533 for (; j < macroOptionals && p < size(); ++j) {
534 // is a [] block following which could be an optional parameter?
535 if (operator[](p)->getChar() != '[') {
536 detachedArgs.push_back(MathData());
540 // found optional argument, look for "]"
541 size_t right = p + 1;
542 for (; right < size(); ++right) {
543 if (operator[](right)->getChar() == ']')
549 if (right < size()) {
550 // add everything between [ and ] as optional argument
551 MathData optarg(begin() + p + 1, begin() + right);
554 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
556 detachedArgs.push_back(optarg[0]->asBraceInset()->cell(0));
558 detachedArgs.push_back(optarg);
559 // place cursor in optional argument of macro
560 if (thisPos >= int(p) && thisPos <= int(right)) {
561 int pos = std::max(0, thisPos - int(p) - 1);
562 std::vector<CursorSlice> x;
563 cur.cutOff(thisSlice, x);
564 cur[thisSlice].pos() = macroPos;
574 // no ] found, so it's not an optional argument
575 // Note: This was "macroPos = p" before, which probably
576 // does not make sense. We want to stop with optional
577 // argument handling instead, so go back to the beginning.
583 // insert normal arguments
584 for (; j < macroNumArgs && p < size(); ++j) {
585 MathAtom & cell = operator[](p);
588 std::vector<CursorSlice> argSlices;
590 if (thisPos == int(p)) {
591 cur.cutOff(thisSlice, argSlices);
594 InsetMathBrace const * brace = cell->asBraceInset();
596 // found brace, convert into argument
597 detachedArgs.push_back(brace->cell(0));
599 // cursor inside of the brace or just in front of?
600 if (thisPos == int(p) && !argSlices.empty()) {
601 argPos = argSlices[0].pos();
602 argSlices.erase(argSlices.begin());
604 } else if (cell->asScriptInset() && j + 1 == macroNumArgs) {
605 // last inset with scripts without braces
606 // -> they belong to the macro, not the argument
607 InsetMathScript * script = cell.nucleus()->asScriptInset();
608 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
609 // nucleus in brace? Unpack!
610 detachedArgs.push_back(script->nuc()[0]->asBraceInset()->cell(0));
612 detachedArgs.push_back(script->nuc());
614 // script will be put around below
615 scriptToPutAround = cell;
617 // this should only happen after loading, so make cursor handling simple
618 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + macroNumArgs)) {
624 array.insert(0, cell);
625 detachedArgs.push_back(array);
628 // put cursor in argument again
629 if (thisPos == int(p)) {
630 cur.append(j, argPos);
631 cur.append(argSlices);
632 cur[thisSlice].pos() = macroPos;
638 // attach arguments back to macro inset
639 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
641 // found tail script? E.g. \foo{a}b^x
642 if (scriptToPutAround.nucleus()) {
643 // put macro into a script inset
644 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
645 = operator[](macroPos);
646 operator[](macroPos) = scriptToPutAround;
648 if (thisPos == int(macroPos))
652 // remove them from the MathData
653 erase(begin() + macroPos + 1, begin() + p);
655 // fix cursor if right of p
656 if (thisPos >= int(p))
657 cur[thisSlice].pos() -= p - (macroPos + 1);
659 // was the macro inset just inserted and was now folded?
660 if (cur[thisSlice].pos() == int(macroPos + 1)
661 && fromInitToNormalMode
662 && macroInset->arity() > 0
663 && thisSlice + 1 == int(cur.depth())) {
664 // then enter it if the cursor was just behind
665 cur[thisSlice].pos() = macroPos;
666 cur.push_back(CursorSlice(*macroInset));
667 macroInset->idxFirst(cur);
670 // FIXME: proper anchor handling, this removes the selection
671 cur.updateInsets(&cur.bottom().inset());
672 cur.clearSelection();
676 int MathData::pos2x(size_type pos) const
678 return pos2x(pos, 0);
682 int MathData::pos2x(size_type pos, int glue) const
685 size_type target = min(pos, size());
686 for (size_type i = 0; i < target; ++i) {
687 const_iterator it = begin() + i;
688 if ((*it)->getChar() == ' ')
690 //lyxerr << "char: " << (*it)->getChar()
691 // << "width: " << (*it)->width() << std::endl;
692 x += atom_dims_[i].wid;
698 MathData::size_type MathData::x2pos(int targetx) const
700 return x2pos(targetx, 0);
704 MathData::size_type MathData::x2pos(int targetx, int glue) const
706 const_iterator it = begin();
709 // find first position after targetx
710 for (; currx < targetx && it < end(); ++it) {
712 if ((*it)->getChar() == ' ')
714 currx += atom_dims_[it - begin()].wid;
718 * If we are not at the beginning of the array, go to the left
719 * of the inset if one of the following two condition holds:
720 * - the current inset is editable (so that the cursor tip is
721 * deeper than us): in this case, we want all intermediate
722 * cursor slices to be before insets;
723 * - the mouse is closer to the left side of the inset than to
725 * See bug 1918 for details.
727 if (it != begin() && currx >= targetx
728 && ((*boost::prior(it))->asNestInset()
729 || abs(lastx - targetx) < abs(currx - targetx))) {
737 int MathData::dist(BufferView const & bv, int x, int y) const
739 return bv.coordCache().getArrays().squareDistance(this, x, y);
743 void MathData::setXY(BufferView & bv, int x, int y) const
745 //lyxerr << "setting position cache for MathData " << this << std::endl;
746 bv.coordCache().arrays().add(this, x, y);
750 Dimension const & MathData::dimension(BufferView const & bv) const
752 return bv.coordCache().getArrays().dim(this);
756 int MathData::xm(BufferView const & bv) const
758 Geometry const & g = bv.coordCache().getArrays().geometry(this);
760 return g.pos.x_ + g.dim.wid / 2;
764 int MathData::ym(BufferView const & bv) const
766 Geometry const & g = bv.coordCache().getArrays().geometry(this);
768 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
772 int MathData::xo(BufferView const & bv) const
774 return bv.coordCache().getArrays().x(this);
778 int MathData::yo(BufferView const & bv) const
780 return bv.coordCache().getArrays().y(this);
784 std::ostream & operator<<(std::ostream & os, MathData const & ar)
786 odocstringstream oss;
787 NormalStream ns(oss);
789 return os << to_utf8(oss.str());
793 odocstream & operator<<(odocstream & os, MathData const & ar)