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"
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>
46 using std::ostringstream;
51 MathData::MathData(const_iterator from, const_iterator to)
56 MathAtom & MathData::operator[](pos_type pos)
58 BOOST_ASSERT(pos < size());
59 return base_type::operator[](pos);
63 MathAtom const & MathData::operator[](pos_type pos) const
65 BOOST_ASSERT(pos < size());
66 return base_type::operator[](pos);
70 void MathData::insert(size_type pos, MathAtom const & t)
72 base_type::insert(begin() + pos, t);
76 void MathData::insert(size_type pos, MathData const & ar)
78 BOOST_ASSERT(pos <= size());
79 base_type::insert(begin() + pos, ar.begin(), ar.end());
83 void MathData::append(MathData const & ar)
89 void MathData::erase(size_type pos)
96 void MathData::erase(iterator pos1, iterator pos2)
98 base_type::erase(pos1, pos2);
102 void MathData::erase(iterator pos)
104 base_type::erase(pos);
108 void MathData::erase(size_type pos1, size_type pos2)
110 base_type::erase(begin() + pos1, begin() + pos2);
114 void MathData::dump2() const
118 for (const_iterator it = begin(); it != end(); ++it)
120 lyxerr << to_utf8(os.str());
124 void MathData::dump() const
128 for (const_iterator it = begin(); it != end(); ++it)
129 ns << '<' << *it << '>';
130 lyxerr << to_utf8(os.str());
134 void MathData::validate(LaTeXFeatures & features) const
136 for (const_iterator it = begin(); it != end(); ++it)
137 (*it)->validate(features);
141 bool MathData::match(MathData const & ar) const
143 return size() == ar.size() && matchpart(ar, 0);
147 bool MathData::matchpart(MathData const & ar, pos_type pos) const
149 if (size() < ar.size() + pos)
151 const_iterator it = begin() + pos;
152 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
153 if (asString(*it) != asString(*jt))
159 void MathData::replace(ReplaceData & rep)
161 for (size_type i = 0; i < size(); ++i) {
162 if (find1(rep.from, i)) {
164 lyxerr << "match found!" << endl;
165 erase(i, i + rep.from.size());
170 // FIXME: temporarily disabled
171 // for (const_iterator it = begin(); it != end(); ++it)
172 // it->nucleus()->replace(rep);
176 bool MathData::find1(MathData const & ar, size_type pos) const
178 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
179 for (size_type i = 0, n = ar.size(); i < n; ++i)
180 if (asString(operator[](pos + i)) != asString(ar[i]))
186 MathData::size_type MathData::find(MathData const & ar) const
188 for (int i = 0, last = size() - ar.size(); i < last; ++i)
195 MathData::size_type MathData::find_last(MathData const & ar) const
197 for (int i = size() - ar.size(); i >= 0; --i)
204 bool MathData::contains(MathData const & ar) const
206 if (find(ar) != size())
208 for (const_iterator it = begin(); it != end(); ++it)
209 if ((*it)->contains(ar))
215 void MathData::touch() const
222 bool isInside(DocIterator const & it, MathData const & ar,
223 pos_type p1, pos_type p2)
225 for (size_t i = 0; i != it.depth(); ++i) {
226 CursorSlice const & sl = it[i];
227 if (sl.inset().inMathed() && &sl.cell() == &ar)
228 return p1 <= sl.pos() && sl.pos() < p2;
237 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
239 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
240 dim = fm.dimension('I');
241 int xascent = fm.dimension('x').ascent();
242 if (xascent >= dim.asc)
243 xascent = (2 * dim.asc) / 3;
245 mindes_ = (3 * xascent) / 4;
246 slevel_ = (4 * xascent) / 5;
247 sshift_ = xascent / 4;
251 // Cache the dimension.
252 mi.base.bv->coordCache().arrays().add(this, dim);
256 const_cast<MathData*>(this)->updateMacros(mi);
262 for (size_t i = 0, n = size(); i != n; ++i) {
263 MathAtom const & at = operator[](i);
265 atom_dims_.push_back(d);
268 kerning_ = at->kerning();
270 // Cache the dimension.
271 mi.base.bv->coordCache().arrays().add(this, dim);
275 void MathData::draw(PainterInfo & pi, int x, int y) const
277 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
278 BufferView & bv = *pi.base.bv;
281 Dimension const & dim = bv.coordCache().getArrays().dim(this);
284 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
288 // don't draw outside the workarea
289 if (y + dim.descent() <= 0
290 || y - dim.ascent() >= bv.workHeight()
291 || x + dim.width() <= 0
292 || x >= bv. workWidth())
295 for (size_t i = 0, n = size(); i != n; ++i) {
296 MathAtom const & at = operator[](i);
297 bv.coordCache().insets().add(at.nucleus(), x, y);
298 at->drawSelection(pi, x, y);
300 x += atom_dims_[i].wid;
305 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
309 for (const_iterator it = begin(); it != end(); ++it) {
310 (*it)->metricsT(mi, d);
316 void MathData::drawT(TextPainter & pain, int x, int y) const
318 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
320 // FIXME: Abdel 16/10/2006
321 // This drawT() method is never used, this is dead code.
323 for (const_iterator it = begin(), et = end(); it != et; ++it) {
324 (*it)->drawT(pain, x, y);
325 //x += (*it)->width_;
331 void MathData::updateMacros(MetricsInfo & mi)
333 Cursor & cur = mi.base.bv->cursor();
335 // go over the array and look for macros
336 for (size_t i = 0; i < size(); ++i) {
337 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
342 macroInset->updateMacro(mi);
343 size_t macroNumArgs = 0;
344 size_t macroOptionals = 0;
345 MacroData const * macro = macroInset->macro();
347 macroNumArgs = macro->numargs();
348 macroOptionals = macro->optionals();
351 // store old and compute new display mode
352 MathMacro::DisplayMode newDisplayMode;
353 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
354 newDisplayMode = macroInset->computeDisplayMode(mi);
356 // arity changed or other reason to detach?
357 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
358 && (macroInset->arity() != macroNumArgs
359 || macroInset->optionals() != macroOptionals
360 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
361 detachMacroParameters(cur, i);
364 // the macro could have been copied while resizing this
365 macroInset = operator[](i).nucleus()->asMacro();
368 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
369 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
370 // put cursor in front of macro
371 int macroSlice = cur.find(macroInset);
372 if (macroSlice != -1)
373 cur.cutOff(macroSlice - 1);
376 // update the display mode
377 macroInset->setDisplayMode(newDisplayMode);
380 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
381 && (macroInset->arity() != macroNumArgs
382 || macroInset->optionals() != macroOptionals)) {
383 // is it a virgin macro which was never attached to parameters?
384 bool fromInitToNormalMode
385 = (oldDisplayMode == MathMacro::DISPLAY_INIT
386 || oldDisplayMode == MathMacro::DISPLAY_NONGREEDY_INIT)
387 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
388 bool greedy = (oldDisplayMode != MathMacro::DISPLAY_NONGREEDY_INIT);
391 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
392 fromInitToNormalMode, greedy);
394 // FIXME: proper anchor handling, this removes the selection
395 cur.updateInsets(&cur.bottom().inset());
396 cur.clearSelection();
399 // give macro the chance to adapt to new situation
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 std::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 std::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
480 // cursor in optional argument of macro?
481 if (curMacroIdx == j) {
483 cur.append(0, curMacroPos);
484 cur[curMacroSlice - 1].pos() = macroPos + 2;
486 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
487 cur.append(argSlices);
488 } else if (cur[curMacroSlice - 1].pos() >= int(p))
489 // cursor right of macro
490 cur[curMacroSlice - 1].pos() += optarg.size();
493 // put them back into the MathData
494 for (; j < detachedArgs.size(); ++j) {
495 MathData const & arg = detachedArgs[j];
496 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
499 insert(p, MathAtom(new InsetMathBrace(arg)));
501 // cursor in j-th argument of macro?
502 if (curMacroIdx == j) {
503 if (operator[](p).nucleus()->asBraceInset()) {
504 cur[curMacroSlice - 1].pos() = p;
505 cur.append(0, curMacroPos);
506 cur.append(argSlices);
508 cur[curMacroSlice - 1].pos() = p; // + macroPos;
509 cur.append(argSlices);
511 } else if (cur[curMacroSlice - 1].pos() >= int(p))
512 ++cur[curMacroSlice - 1].pos();
517 // FIXME: proper anchor handling, this removes the selection
518 cur.clearSelection();
519 cur.updateInsets(&cur.bottom().inset());
523 void MathData::attachMacroParameters(Cursor & cur,
524 const size_type macroPos, const size_type macroNumArgs,
525 const int macroOptionals, const bool fromInitToNormalMode,
528 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
530 // start at atom behind the macro again, maybe with some new arguments from above
531 // to add them back into the macro inset
532 size_t p = macroPos + 1;
533 std::vector<MathData> detachedArgs;
534 MathAtom scriptToPutAround;
536 // find cursor slice again
537 int thisSlice = cur.find(*this);
540 thisPos = cur[thisSlice].pos();
542 // find arguments behind the macro
544 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
545 macroPos, thisPos, thisSlice);
546 collectParameters(cur, macroNumArgs, detachedArgs, p,
548 macroPos, thisPos, thisSlice);
551 // attach arguments back to macro inset
552 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
554 // found tail script? E.g. \foo{a}b^x
555 if (scriptToPutAround.nucleus()) {
556 // put macro into a script inset
557 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0]
558 = operator[](macroPos);
559 operator[](macroPos) = scriptToPutAround;
561 if (thisPos == int(macroPos))
565 // remove them from the MathData
566 erase(begin() + macroPos + 1, begin() + p);
569 // no need to update the cursor?
573 // fix cursor if right of p
574 if (thisPos >= int(p))
575 cur[thisSlice].pos() -= p - (macroPos + 1);
577 // was the macro inset just inserted and was now folded?
578 if (cur[thisSlice].pos() == int(macroPos + 1)
579 && fromInitToNormalMode
580 && macroInset->arity() > 0
581 && thisSlice + 1 == int(cur.depth())) {
582 // then enter it if the cursor was just behind
583 cur[thisSlice].pos() = macroPos;
584 cur.push_back(CursorSlice(*macroInset));
585 macroInset->idxFirst(cur);
590 void MathData::collectOptionalParameters(Cursor & cur,
591 const size_type numOptionalParams, std::vector<MathData> & params,
592 size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
594 // insert optional arguments?
595 while (params.size() < numOptionalParams && pos < size()) {
596 // is a [] block following which could be an optional parameter?
597 if (operator[](pos)->getChar() != '[')
600 // found possible optional argument, look for "]"
601 size_t right = pos + 1;
602 for (; right < size(); ++right) {
603 if (operator[](right)->getChar() == ']')
609 if (right >= size()) {
610 // no ] found, so it's not an optional argument
614 // add everything between [ and ] as optional argument
615 MathData optarg(begin() + pos + 1, begin() + right);
619 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
621 params.push_back(optarg[0]->asBraceInset()->cell(0));
623 params.push_back(optarg);
625 // place cursor in optional argument of macro
627 && thisPos >= int(pos) && thisPos <= int(right)) {
628 int paramPos = std::max(0, thisPos - int(pos) - 1);
629 std::vector<CursorSlice> x;
630 cur.cutOff(thisSlice, x);
631 cur[thisSlice].pos() = macroPos;
633 paramPos = x[0].pos();
636 cur.append(0, paramPos);
642 // fill up empty optional parameters
643 while (params.size() < numOptionalParams) {
644 params.push_back(MathData());
649 void MathData::collectParameters(Cursor & cur,
650 const size_type numParams, std::vector<MathData> & params,
651 size_t & pos, MathAtom & scriptToPutAround,
652 const pos_type macroPos, const int thisPos, const int thisSlice)
654 // insert normal arguments
655 for (; params.size() < numParams && pos < size();) {
656 MathAtom & cell = operator[](pos);
659 std::vector<CursorSlice> argSlices;
661 if (thisSlice != -1 && thisPos == int(pos)) {
662 cur.cutOff(thisSlice, argSlices);
665 // which kind of parameter is it? In {}? With index x^n?
666 InsetMathBrace const * brace = cell->asBraceInset();
668 // found brace, convert into argument
669 params.push_back(brace->cell(0));
671 // cursor inside of the brace or just in front of?
672 if (thisPos == int(pos) && !argSlices.empty()) {
673 argPos = argSlices[0].pos();
674 argSlices.erase(argSlices.begin());
676 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
677 // last inset with scripts without braces
678 // -> they belong to the macro, not the argument
679 InsetMathScript * script = cell.nucleus()->asScriptInset();
680 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
681 // nucleus in brace? Unpack!
682 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
684 params.push_back(script->nuc());
686 // script will be put around below
687 scriptToPutAround = cell;
689 // this should only happen after loading, so make cursor handling simple
690 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
695 // the simplest case: plain inset
697 array.insert(0, cell);
698 params.push_back(array);
701 // put cursor in argument again
702 if (thisSlice != - 1 && thisPos == int(pos)) {
703 cur.append(params.size() - 1, argPos);
704 cur.append(argSlices);
705 cur[thisSlice].pos() = macroPos;
713 int MathData::pos2x(size_type pos) const
715 return pos2x(pos, 0);
719 int MathData::pos2x(size_type pos, int glue) const
722 size_type target = min(pos, size());
723 for (size_type i = 0; i < target; ++i) {
724 const_iterator it = begin() + i;
725 if ((*it)->getChar() == ' ')
727 //lyxerr << "char: " << (*it)->getChar()
728 // << "width: " << (*it)->width() << std::endl;
729 x += atom_dims_[i].wid;
735 MathData::size_type MathData::x2pos(int targetx) const
737 return x2pos(targetx, 0);
741 MathData::size_type MathData::x2pos(int targetx, int glue) const
743 const_iterator it = begin();
746 // find first position after targetx
747 for (; currx < targetx && it < end(); ++it) {
749 if ((*it)->getChar() == ' ')
751 currx += atom_dims_[it - begin()].wid;
755 * If we are not at the beginning of the array, go to the left
756 * of the inset if one of the following two condition holds:
757 * - the current inset is editable (so that the cursor tip is
758 * deeper than us): in this case, we want all intermediate
759 * cursor slices to be before insets;
760 * - the mouse is closer to the left side of the inset than to
762 * See bug 1918 for details.
764 if (it != begin() && currx >= targetx
765 && ((*boost::prior(it))->asNestInset()
766 || abs(lastx - targetx) < abs(currx - targetx))) {
774 int MathData::dist(BufferView const & bv, int x, int y) const
776 return bv.coordCache().getArrays().squareDistance(this, x, y);
780 void MathData::setXY(BufferView & bv, int x, int y) const
782 //lyxerr << "setting position cache for MathData " << this << std::endl;
783 bv.coordCache().arrays().add(this, x, y);
787 Dimension const & MathData::dimension(BufferView const & bv) const
789 return bv.coordCache().getArrays().dim(this);
793 int MathData::xm(BufferView const & bv) const
795 Geometry const & g = bv.coordCache().getArrays().geometry(this);
797 return g.pos.x_ + g.dim.wid / 2;
801 int MathData::ym(BufferView const & bv) const
803 Geometry const & g = bv.coordCache().getArrays().geometry(this);
805 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
809 int MathData::xo(BufferView const & bv) const
811 return bv.coordCache().getArrays().x(this);
815 int MathData::yo(BufferView const & bv) const
817 return bv.coordCache().getArrays().y(this);
821 std::ostream & operator<<(std::ostream & os, MathData const & ar)
823 odocstringstream oss;
824 NormalStream ns(oss);
826 return os << to_utf8(oss.str());
830 odocstream & operator<<(odocstream & os, MathData const & ar)