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"
31 #include "mathed/InsetMathUnknown.h"
33 #include "frontends/FontMetrics.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lyxalgo.h"
48 MathData::MathData(Buffer * buf, const_iterator from, const_iterator to)
49 : base_type(from, to), minasc_(0), mindes_(0), slevel_(0),
50 sshift_(0), kerning_(0), buffer_(buf)
54 MathAtom & MathData::operator[](pos_type pos)
56 LBUFERR(pos < size());
57 return base_type::operator[](pos);
61 MathAtom const & MathData::operator[](pos_type pos) const
63 LBUFERR(pos < size());
64 return base_type::operator[](pos);
68 void MathData::insert(size_type pos, MathAtom const & t)
70 LBUFERR(pos <= size());
71 base_type::insert(begin() + pos, t);
75 void MathData::insert(size_type pos, MathData const & ar)
77 LBUFERR(pos <= size());
78 base_type::insert(begin() + pos, ar.begin(), ar.end());
82 void MathData::append(MathData const & ar)
88 void MathData::erase(size_type pos)
95 void MathData::erase(iterator pos1, iterator pos2)
97 base_type::erase(pos1, pos2);
101 void MathData::erase(iterator pos)
103 base_type::erase(pos);
107 void MathData::erase(size_type pos1, size_type pos2)
109 base_type::erase(begin() + pos1, begin() + pos2);
113 void MathData::dump2() const
117 for (const_iterator it = begin(); it != end(); ++it)
119 lyxerr << to_utf8(os.str());
123 void MathData::dump() const
127 for (const_iterator it = begin(); it != end(); ++it)
128 ns << '<' << *it << '>';
129 lyxerr << to_utf8(os.str());
133 void MathData::validate(LaTeXFeatures & features) const
135 for (const_iterator it = begin(); it != end(); ++it)
136 (*it)->validate(features);
140 bool MathData::match(MathData const & ar) const
142 return size() == ar.size() && matchpart(ar, 0);
146 bool MathData::matchpart(MathData const & ar, pos_type pos) const
148 if (size() < ar.size() + pos)
150 const_iterator it = begin() + pos;
151 for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
152 if (asString(*it) != asString(*jt))
158 void MathData::replace(ReplaceData & rep)
160 for (size_type i = 0; i < size(); ++i) {
161 if (find1(rep.from, i)) {
163 lyxerr << "match found!" << endl;
164 erase(i, i + rep.from.size());
169 // FIXME: temporarily disabled
170 // for (const_iterator it = begin(); it != end(); ++it)
171 // it->nucleus()->replace(rep);
175 bool MathData::find1(MathData const & ar, size_type pos) const
177 lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
178 for (size_type i = 0, n = ar.size(); i < n; ++i)
179 if (asString(operator[](pos + i)) != asString(ar[i]))
185 MathData::size_type MathData::find(MathData const & ar) const
187 for (int i = 0, last = size() - ar.size(); i < last; ++i)
194 MathData::size_type MathData::find_last(MathData const & ar) const
196 for (int i = size() - ar.size(); i >= 0; --i)
203 bool MathData::contains(MathData const & ar) const
205 if (find(ar) != size())
207 for (const_iterator it = begin(); it != end(); ++it)
208 if ((*it)->contains(ar))
214 void MathData::touch() const
219 bool MathData::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
221 bool has_contents = false;
222 BufferView * bv = mi.base.bv;
223 MathData * ar = const_cast<MathData*>(this);
224 ar->updateMacros(&bv->cursor(), mi.macrocontext,
225 InternalUpdate, mi.base.macro_nesting);
228 // FIXME: for completion, try to insert the relevant data in the
229 // mathrow (like is done for text rows). We could add a pair of
230 // InsetMathColor inset, but these come with extra spacing of
232 DocIterator const & inlineCompletionPos = bv->inlineCompletionPos();
233 bool const has_completion = inlineCompletionPos.inMathed()
234 && &inlineCompletionPos.cell() == this;
235 size_t const compl_pos = has_completion ? inlineCompletionPos.pos() : 0;
237 for (size_t i = 0 ; i < size() ; ++i) {
238 has_contents |= (*this)[i]->addToMathRow(mrow, mi);
239 if (i + 1 == compl_pos) {
240 mrow.back().compl_text = bv->inlineCompletion();
241 mrow.back().compl_unique_to = bv->inlineCompletionUniqueChars();
251 bool isInside(DocIterator const & it, MathData const & ar,
252 pos_type p1, pos_type p2)
254 for (size_t i = 0; i != it.depth(); ++i) {
255 CursorSlice const & sl = it[i];
256 if (sl.inset().inMathed() && &sl.cell() == &ar)
257 return p1 <= sl.pos() && sl.pos() < p2;
266 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
268 frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
269 dim = fm.dimension('I');
270 int xascent = fm.dimension('x').ascent();
271 if (xascent >= dim.asc)
272 xascent = (2 * dim.asc) / 3;
274 mindes_ = (3 * xascent) / 4;
275 slevel_ = (4 * xascent) / 5;
276 sshift_ = xascent / 4;
278 MathRow mrow(mi, this);
279 mrow_cache_[mi.base.bv] = mrow;
280 mrow.metrics(mi, dim);
281 kerning_ = mrow.kerning(mi.base.bv);
283 // Cache the dimension.
284 mi.base.bv->coordCache().arrays().add(this, dim);
288 void MathData::draw(PainterInfo & pi, int const x, int const y) const
290 //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
291 BufferView & bv = *pi.base.bv;
294 Dimension const & dim = bv.coordCache().getArrays().dim(this);
296 // don't draw outside the workarea
297 if (y + dim.descent() <= 0
298 || y - dim.ascent() >= bv.workHeight()
299 || x + dim.width() <= 0
300 || x >= bv. workWidth())
303 MathRow const & mrow = mrow_cache_[pi.base.bv];
308 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
312 for (const_iterator it = begin(); it != end(); ++it) {
313 (*it)->metricsT(mi, d);
319 void MathData::drawT(TextPainter & pain, int x, int y) const
321 //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
323 // FIXME: Abdel 16/10/2006
324 // This drawT() method is never used, this is dead code.
326 for (const_iterator it = begin(), et = end(); it != et; ++it) {
327 (*it)->drawT(pain, x, y);
328 //x += (*it)->width_;
334 void MathData::updateBuffer(ParIterator const & it, UpdateType utype)
337 for (size_t i = 0, n = size(); i != n; ++i) {
338 MathAtom & at = operator[](i);
339 at.nucleus()->updateBuffer(it, utype);
344 void MathData::updateMacros(Cursor * cur, MacroContext const & mc,
345 UpdateType utype, int nesting)
347 // If we are editing a macro, we cannot update it immediately,
348 // otherwise wrong undo steps will be recorded (bug 6208).
349 InsetMath const * inmath = cur ? cur->inset().asInsetMath() : 0;
350 MathMacro const * inmacro = inmath ? inmath->asMacro() : 0;
351 docstring const edited_name = inmacro ? inmacro->name() : docstring();
353 // go over the array and look for macros
354 for (size_t i = 0; i < size(); ++i) {
355 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
356 if (!macroInset || macroInset->macroName().empty()
357 || macroInset->macroName()[0] == '^'
358 || macroInset->macroName()[0] == '_'
359 || (macroInset->name() == edited_name
360 && macroInset->displayMode() ==
361 MathMacro::DISPLAY_UNFOLDED))
365 macroInset->updateMacro(mc);
366 size_t macroNumArgs = 0;
367 size_t macroOptionals = 0;
368 MacroData const * macro = macroInset->macro();
370 macroNumArgs = macro->numargs();
371 macroOptionals = macro->optionals();
374 // store old and compute new display mode
375 MathMacro::DisplayMode newDisplayMode;
376 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
377 newDisplayMode = macroInset->computeDisplayMode();
379 // arity changed or other reason to detach?
380 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
381 && (macroInset->arity() != macroNumArgs
382 || macroInset->optionals() != macroOptionals
383 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED))
384 detachMacroParameters(cur, i);
386 // the macro could have been copied while resizing this
387 macroInset = operator[](i).nucleus()->asMacro();
390 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
391 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
392 // put cursor in front of macro
394 int macroSlice = cur->find(macroInset);
395 if (macroSlice != -1)
396 cur->cutOff(macroSlice - 1);
400 // update the display mode
401 size_t appetite = macroInset->appetite();
402 macroInset->setDisplayMode(newDisplayMode);
405 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
406 && (macroInset->arity() != macroNumArgs
407 || macroInset->optionals() != macroOptionals)) {
408 // is it a virgin macro which was never attached to parameters?
409 bool fromInitToNormalMode
410 = (oldDisplayMode == MathMacro::DISPLAY_INIT
411 || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
412 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
414 // if the macro was entered interactively (i.e. not by paste or during
415 // loading), it should not be greedy, but the cursor should
416 // automatically jump into the macro when behind
417 bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
420 attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
421 fromInitToNormalMode, interactive, appetite);
424 cur->updateInsets(&cur->bottom().inset());
427 // Give macro the chance to adapt to new situation.
428 // The macroInset could be invalid now because it was put into a script
429 // inset and therefore "deep" copied. So get it again from the MathData.
430 InsetMath * inset = operator[](i).nucleus();
431 if (inset->asScriptInset())
432 inset = inset->asScriptInset()->nuc()[0].nucleus();
433 LASSERT(inset->asMacro(), continue);
434 inset->asMacro()->updateRepresentation(cur, mc, utype, nesting + 1);
439 void MathData::detachMacroParameters(DocIterator * cur, const size_type macroPos)
441 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
442 // We store this now, because the inset pointer will be invalidated in the scond loop below
443 size_t const optionals = macroInset->optionals();
445 // detach all arguments
446 vector<MathData> detachedArgs;
447 if (macroPos + 1 == size())
448 // strip arguments if we are at the MathData end
449 macroInset->detachArguments(detachedArgs, true);
451 macroInset->detachArguments(detachedArgs, false);
454 int curMacroSlice = -1;
456 curMacroSlice = cur->find(macroInset);
457 idx_type curMacroIdx = -1;
458 pos_type curMacroPos = -1;
459 vector<CursorSlice> argSlices;
460 if (curMacroSlice != -1) {
461 curMacroPos = (*cur)[curMacroSlice].pos();
462 curMacroIdx = (*cur)[curMacroSlice].idx();
463 cur->cutOff(curMacroSlice, argSlices);
467 // only [] after the last non-empty argument can be dropped later
468 size_t lastNonEmptyOptional = 0;
469 for (size_t l = 0; l < detachedArgs.size() && l < optionals; ++l) {
470 if (!detachedArgs[l].empty())
471 lastNonEmptyOptional = l;
474 // optional arguments to be put back?
475 pos_type p = macroPos + 1;
477 // We do not want to use macroInset below, the insert() call in
478 // the loop will invalidate it.
480 for (; j < detachedArgs.size() && j < optionals; ++j) {
481 // another non-empty parameter follows?
482 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
484 // then we can drop empty optional parameters
485 if (detachedArgs[j].empty() && canDropEmptyOptional) {
486 if (curMacroIdx == j)
487 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
491 // Otherwise we don't drop an empty optional, put it back normally
493 asArray(from_ascii("[]"), optarg);
494 MathData & arg = detachedArgs[j];
496 // look for "]", i.e. put a brace around?
497 InsetMathBrace * brace = 0;
498 for (size_t q = 0; q < arg.size(); ++q) {
499 if (arg[q]->getChar() == ']') {
501 brace = new InsetMathBrace(buffer_);
506 // put arg between []
508 brace->cell(0) = arg;
509 optarg.insert(1, MathAtom(brace));
511 optarg.insert(1, arg);
513 // insert it into the array
518 if (curMacroSlice == -1)
521 // cursor in optional argument of macro?
522 if (curMacroIdx == j) {
524 cur->append(0, curMacroPos);
525 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
527 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
528 cur->append(argSlices);
529 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
530 // cursor right of macro
531 (*cur)[curMacroSlice - 1].pos() += optarg.size();
534 // put them back into the MathData
535 for (; j < detachedArgs.size(); ++j, ++p) {
536 MathData const & arg = detachedArgs[j];
538 && !arg[0]->asScriptInset()
539 && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
542 insert(p, MathAtom(new InsetMathBrace(arg)));
545 if (curMacroSlice == -1)
548 // cursor in j-th argument of macro?
549 if (curMacroIdx == j) {
550 if (operator[](p).nucleus()->asBraceInset()) {
551 (*cur)[curMacroSlice - 1].pos() = p;
552 cur->append(0, curMacroPos);
553 cur->append(argSlices);
555 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
556 cur->append(argSlices);
558 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
559 ++(*cur)[curMacroSlice - 1].pos();
563 cur->updateInsets(&cur->bottom().inset());
567 void MathData::attachMacroParameters(Cursor * cur,
568 const size_type macroPos, const size_type macroNumArgs,
569 const int macroOptionals, const bool fromInitToNormalMode,
570 const bool interactiveInit, const size_t appetite)
572 MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
574 // start at atom behind the macro again, maybe with some new arguments
575 // from the detach phase above, to add them back into the macro inset
576 size_t p = macroPos + 1;
577 vector<MathData> detachedArgs;
578 MathAtom scriptToPutAround;
580 // find cursor slice again of this MathData
583 thisSlice = cur->find(*this);
586 thisPos = (*cur)[thisSlice].pos();
588 // find arguments behind the macro
589 if (!interactiveInit) {
590 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
591 scriptToPutAround, macroPos, thisPos, thisSlice);
593 collectParameters(cur, macroNumArgs, detachedArgs, p,
594 scriptToPutAround, macroPos, thisPos, thisSlice, appetite);
596 // attach arguments back to macro inset
597 macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
599 // found tail script? E.g. \foo{a}b^x
600 if (scriptToPutAround.nucleus()) {
601 InsetMathScript * scriptInset =
602 scriptToPutAround.nucleus()->asScriptInset();
603 // In the math parser we remove empty braces in the base
604 // of a script inset, but we have to restore them here.
605 if (scriptInset->nuc().empty()) {
607 scriptInset->nuc().push_back(
608 MathAtom(new InsetMathBrace(ar)));
610 // put macro into a script inset
611 scriptInset->nuc()[0] = operator[](macroPos);
612 operator[](macroPos) = scriptToPutAround;
614 // go into the script inset nucleus
615 if (cur && thisPos == int(macroPos))
618 // get pointer to "deep" copied macro inset
619 scriptInset = operator[](macroPos).nucleus()->asScriptInset();
620 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
623 // remove them from the MathData
624 erase(macroPos + 1, p);
626 // cursor outside this MathData?
630 // fix cursor if right of p
631 if (thisPos >= int(p))
632 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
634 // was the macro inset just inserted interactively and was now folded
635 // and the cursor is just behind?
636 if ((*cur)[thisSlice].pos() == int(macroPos + 1)
638 && fromInitToNormalMode
639 && macroInset->arity() > 0
640 && thisSlice + 1 == int(cur->depth())) {
641 // then enter it if the cursor was just behind
642 (*cur)[thisSlice].pos() = macroPos;
643 cur->push_back(CursorSlice(*macroInset));
644 macroInset->idxFirst(*cur);
649 void MathData::collectOptionalParameters(Cursor * cur,
650 const size_type numOptionalParams, vector<MathData> & params,
651 size_t & pos, MathAtom & scriptToPutAround,
652 const pos_type macroPos, const int thisPos, const int thisSlice)
654 Buffer * buf = cur ? cur->buffer() : 0;
655 // insert optional arguments?
656 while (params.size() < numOptionalParams
658 && !scriptToPutAround.nucleus()) {
659 // is a [] block following which could be an optional parameter?
660 if (operator[](pos)->getChar() != '[')
663 // found possible optional argument, look for pairing "]"
665 size_t right = pos + 1;
666 for (; right < size(); ++right) {
667 MathAtom & cell = operator[](right);
669 if (cell->getChar() == '[')
671 else if (cell->getChar() == ']' && --count == 0)
675 // maybe "]" with a script around?
676 InsetMathScript * script = cell.nucleus()->asScriptInset();
679 if (script->nuc().size() != 1)
681 if (script->nuc()[0]->getChar() == ']') {
682 // script will be put around the macro later
683 scriptToPutAround = cell;
689 if (right >= size()) {
690 // no ] found, so it's not an optional argument
694 // add everything between [ and ] as optional argument
695 MathData optarg(buf, begin() + pos + 1, begin() + right);
699 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
701 params.push_back(optarg[0]->asBraceInset()->cell(0));
703 params.push_back(optarg);
705 // place cursor in optional argument of macro
707 && thisPos >= int(pos) && thisPos <= int(right)) {
708 int paramPos = max(0, thisPos - int(pos) - 1);
709 vector<CursorSlice> x;
710 cur->cutOff(thisSlice, x);
711 (*cur)[thisSlice].pos() = macroPos;
713 paramPos = x[0].pos();
716 cur->append(0, paramPos);
722 // fill up empty optional parameters
723 while (params.size() < numOptionalParams)
724 params.push_back(MathData());
728 void MathData::collectParameters(Cursor * cur,
729 const size_type numParams, vector<MathData> & params,
730 size_t & pos, MathAtom & scriptToPutAround,
731 const pos_type macroPos, const int thisPos, const int thisSlice,
732 const size_t appetite)
734 size_t startSize = params.size();
736 // insert normal arguments
737 while (params.size() < numParams
738 && params.size() - startSize < appetite
740 && !scriptToPutAround.nucleus()) {
741 MathAtom & cell = operator[](pos);
744 vector<CursorSlice> argSlices;
746 if (thisSlice != -1 && thisPos == int(pos))
747 cur->cutOff(thisSlice, argSlices);
749 // which kind of parameter is it? In {}? With index x^n?
750 InsetMathBrace const * brace = cell->asBraceInset();
752 // found brace, convert into argument
753 params.push_back(brace->cell(0));
755 // cursor inside of the brace or just in front of?
756 if (thisPos == int(pos) && !argSlices.empty()) {
757 argPos = argSlices[0].pos();
758 argSlices.erase(argSlices.begin());
760 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
761 // last inset with scripts without braces
762 // -> they belong to the macro, not the argument
763 InsetMathScript * script = cell.nucleus()->asScriptInset();
764 if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
765 // nucleus in brace? Unpack!
766 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
768 params.push_back(script->nuc());
770 // script will be put around below
771 scriptToPutAround = cell;
773 // this should only happen after loading, so make cursor handling simple
774 if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
780 // the simplest case: plain inset
782 array.insert(0, cell);
783 params.push_back(array);
786 // put cursor in argument again
787 if (thisSlice != - 1 && thisPos == int(pos)) {
788 cur->append(params.size() - 1, argPos);
789 cur->append(argSlices);
790 (*cur)[thisSlice].pos() = macroPos;
798 int MathData::pos2x(BufferView const * bv, size_type pos) const
801 size_type target = min(pos, size());
802 CoordCache::Insets const & coords = bv->coordCache().getInsets();
803 for (size_type i = 0; i < target; ++i) {
804 const_iterator it = begin() + i;
805 //lyxerr << "char: " << (*it)->getChar()
806 // << "width: " << (*it)->width() << endl;
807 x += coords.dim((*it).nucleus()).wid;
813 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
815 const_iterator it = begin();
818 CoordCache::Insets const & coords = bv->coordCache().getInsets();
819 // find first position after targetx
820 for (; currx < targetx && it != end(); ++it) {
822 currx += coords.dim((*it).nucleus()).wid;
826 * If we are not at the beginning of the array, go to the left
827 * of the inset if one of the following two condition holds:
828 * - the current inset is editable (so that the cursor tip is
829 * deeper than us): in this case, we want all intermediate
830 * cursor slices to be before insets;
831 * - the mouse is closer to the left side of the inset than to
833 * See bug 1918 for details.
835 if (it != begin() && currx >= targetx
836 && ((*prev(it, 1))->asNestInset()
837 || abs(lastx - targetx) < abs(currx - targetx))) {
845 int MathData::dist(BufferView const & bv, int x, int y) const
847 return bv.coordCache().getArrays().squareDistance(this, x, y);
851 void MathData::setXY(BufferView & bv, int x, int y) const
853 //lyxerr << "setting position cache for MathData " << this << endl;
854 bv.coordCache().arrays().add(this, x, y);
858 Dimension const & MathData::dimension(BufferView const & bv) const
860 return bv.coordCache().getArrays().dim(this);
864 int MathData::xm(BufferView const & bv) const
866 Geometry const & g = bv.coordCache().getArrays().geometry(this);
868 return g.pos.x_ + g.dim.wid / 2;
872 int MathData::ym(BufferView const & bv) const
874 Geometry const & g = bv.coordCache().getArrays().geometry(this);
876 return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
880 int MathData::xo(BufferView const & bv) const
882 return bv.coordCache().getArrays().x(this);
886 int MathData::yo(BufferView const & bv) const
888 return bv.coordCache().getArrays().y(this);
892 ostream & operator<<(ostream & os, MathData const & ar)
894 odocstringstream oss;
895 NormalStream ns(oss);
897 return os << to_utf8(oss.str());
901 odocstream & operator<<(odocstream & os, MathData const & ar)