3 * Purpose: Interaction for mathed
4 * Author: Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 * Created: January 1996
6 * Description: Math interaction for a WYSIWYG math editor.
8 * Dependencies: Xlib, XForms
10 * Copyright: 1996, Alejandro Aguilar Sierra
12 * Version: 0.8beta, Math & Lyx project.
14 * You are free to use and modify this code under the terms of
15 * the GNU General Public Licence version 2 or later.
22 #pragma implementation
25 #include "support/lstrings.h"
26 #include "support/LAssert.h"
28 #include "frontends/Painter.h"
29 #include "math_cursor.h"
30 #include "formulabase.h"
31 #include "funcrequest.h"
32 #include "math_autocorrect.h"
33 #include "math_braceinset.h"
34 #include "math_commentinset.h"
35 #include "math_charinset.h"
36 #include "math_extern.h"
37 #include "math_factory.h"
38 #include "math_fontinset.h"
39 #include "math_gridinset.h"
40 #include "math_iterator.h"
41 #include "math_macroarg.h"
42 #include "math_macrotemplate.h"
43 #include "math_mathmlstream.h"
44 #include "math_scriptinset.h"
45 #include "math_spaceinset.h"
46 #include "math_support.h"
47 #include "math_unknowninset.h"
59 using std::ostringstream;
63 // matheds own cut buffer
67 MathCursor::MathCursor(InsetFormulaBase * formula, bool front)
68 : formula_(formula), autocorrect_(false), selection_(false), targetx_(-1)
70 front ? first() : last();
75 MathCursor::~MathCursor()
77 // ensure that 'notifyCursorLeave' is called
83 void MathCursor::push(MathAtom & t)
85 Cursor_.push_back(MathCursorPos(t.nucleus()));
89 void MathCursor::pushLeft(MathAtom & t)
91 //lyxerr << "Entering atom " << t << " left\n";
93 t->idxFirst(idx(), pos());
97 void MathCursor::pushRight(MathAtom & t)
99 //lyxerr << "Entering atom " << t << " right\n";
102 t->idxLast(idx(), pos());
106 bool MathCursor::popLeft()
108 //cerr << "Leaving atom to the left\n";
111 par()->notifyCursorLeaves(idx());
114 par()->notifyCursorLeaves(idx());
120 bool MathCursor::popRight()
122 //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " right\n";
125 par()->notifyCursorLeaves(idx());
128 par()->notifyCursorLeaves(idx());
137 void MathCursor::dump(char const * what) const
139 lyxerr << "MC: " << what << endl;
140 lyxerr << " Cursor: " << depth() << endl;
141 for (unsigned i = 0; i < depth(); ++i)
142 lyxerr << " i: " << i << ' ' << Cursor_[i] << endl;
143 lyxerr << " Anchor: " << Anchor_.size() << endl;
144 for (unsigned i = 0; i < Anchor_.size(); ++i)
145 lyxerr << " i: " << i << ' ' << Anchor_[i] << endl;
146 lyxerr << " sel: " << selection_ << endl;
149 void MathCursor::dump(char const *) const {}
153 bool MathCursor::isInside(MathInset const * p) const
155 for (unsigned i = 0; i < depth(); ++i)
156 if (Cursor_[i].par_ == p)
162 bool MathCursor::openable(MathAtom const & t, bool sel) const
171 // we can't move into anything new during selection
172 if (depth() == Anchor_.size())
174 if (t.operator->() != Anchor_[depth()].par_)
181 bool MathCursor::inNucleus() const
183 return par()->asScriptInset() && idx() == 2;
187 bool MathCursor::posLeft()
196 bool MathCursor::posRight()
205 bool MathCursor::left(bool sel)
208 autocorrect_ = false;
209 targetx_ = -1; // "no target"
216 if (hasPrevAtom() && openable(prevAtom(), sel)) {
217 pushRight(prevAtom());
221 return posLeft() || idxLeft() || popLeft() || selection_;
225 bool MathCursor::right(bool sel)
228 autocorrect_ = false;
229 targetx_ = -1; // "no target"
236 if (hasNextAtom() && openable(nextAtom(), sel)) {
237 pushLeft(nextAtom());
241 return posRight() || idxRight() || popRight() || selection_;
245 void MathCursor::first()
248 push(formula_->par());
249 par()->idxFirst(idx(), pos());
253 void MathCursor::last()
256 push(formula_->par());
257 par()->idxLast(idx(), pos());
262 (MathIterator const & cursor, MathIterator const & anchor)
264 // avoid deeper nested insets when selecting
265 if (cursor.size() > anchor.size())
268 // anchor might be deeper, should have same path then
269 for (MathIterator::size_type i = 0; i < cursor.size(); ++i)
270 if (cursor[i].par_ != anchor[i].par_)
273 // position should be ok.
278 void MathCursor::setPos(int x, int y)
281 bool res = bruteFind(x, y,
282 formula()->xlow(), formula()->xhigh(),
283 formula()->ylow(), formula()->yhigh());
285 // this can happen on creation of "math-display"
289 targetx_ = -1; // "no target"
295 bool MathCursor::home(bool sel)
298 autocorrect_ = false;
301 if (!par()->idxHome(idx(), pos()))
304 targetx_ = -1; // "no target"
309 bool MathCursor::end(bool sel)
312 autocorrect_ = false;
315 if (!par()->idxEnd(idx(), pos()))
318 targetx_ = -1; // "no target"
323 void MathCursor::plainErase()
325 array().erase(pos());
329 void MathCursor::markInsert()
331 //lyxerr << "inserting mark\n";
332 array().insert(pos(), MathAtom(new MathCharInset(0)));
336 void MathCursor::markErase()
338 //lyxerr << "deleting mark\n";
339 array().erase(pos());
343 void MathCursor::plainInsert(MathAtom const & t)
346 array().insert(pos(), t);
351 void MathCursor::insert(string const & str)
353 //lyxerr << "inserting '" << str << "'\n";
355 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
356 plainInsert(MathAtom(new MathCharInset(*it)));
360 void MathCursor::insert(char c)
362 //lyxerr << "inserting '" << c << "'\n";
364 plainInsert(MathAtom(new MathCharInset(c)));
368 void MathCursor::insert(MathAtom const & t)
376 void MathCursor::niceInsert(string const & t)
378 MathArray ar = asArray(t);
386 void MathCursor::niceInsert(MathAtom const & t)
389 string safe = grabAndEraseSelection();
391 // enter the new inset and move the contents of the selection if possible
394 pushLeft(nextAtom());
400 void MathCursor::insert(MathArray const & ar)
405 array().insert(pos(), ar);
410 void MathCursor::paste(string const & data)
412 dispatch(FuncRequest(LFUN_PASTE, data));
416 void MathCursor::backspace()
418 autocorrect_ = false;
431 MathUnknownInset * p = activeMacro();
432 if (p->name().size() > 1) {
433 p->setName(p->name().substr(0, p->name().size() - 1));
443 void MathCursor::erase()
445 autocorrect_ = false;
454 // delete empty cells if possible
456 if (par()->idxDelete(idx()))
459 // old behaviour when in last position of cell
460 if (pos() == size()) {
461 par()->idxGlue(idx());
469 bool MathCursor::up(bool sel)
474 MathIterator save = Cursor_;
478 autocorrect_ = false;
483 bool MathCursor::down(bool sel)
488 MathIterator save = Cursor_;
492 autocorrect_ = false;
497 void MathCursor::macroModeClose()
501 MathUnknownInset * p = activeMacro();
503 string s = p->name();
505 array().erase(pos());
507 // do nothing if the macro name is empty
511 string name = s.substr(1);
513 // prevent entering of recursive macros
514 if (formula()->lyxCode() == Inset::MATHMACRO_CODE
515 && formula()->getInsetName() == name)
516 lyxerr << "can't enter recursive macro\n";
518 niceInsert(createMathInset(name));
522 string MathCursor::macroName() const
524 return inMacroMode() ? activeMacro()->name() : string();
528 void MathCursor::selClear()
535 void MathCursor::selCopy()
539 theCutBuffer = grabSelection();
542 theCutBuffer.erase();
547 void MathCursor::selCut()
550 theCutBuffer = grabAndEraseSelection();
554 void MathCursor::selDel()
564 void MathCursor::selPaste()
574 void MathCursor::selHandle(bool sel)
576 if (sel == selection_)
584 void MathCursor::selStart()
594 void MathCursor::selClearOrDel()
596 if (lyxrc.auto_region_delete)
603 void MathCursor::drawSelection(MathPainterInfo & pi) const
609 getSelection(i1, i2);
610 i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
614 void MathCursor::handleNest(MathAtom const & a)
617 at.nucleus()->cell(0) = asArray(grabAndEraseSelection());
619 pushRight(prevAtom());
623 void MathCursor::getPos(int & x, int & y) const
625 par()->getPos(idx(), pos(), x, y);
629 int MathCursor::targetX() const
639 MathInset * MathCursor::par() const
641 return cursor().par_;
645 InsetFormulaBase * MathCursor::formula() const
651 MathCursor::idx_type MathCursor::idx() const
653 return cursor().idx_;
657 MathCursor::idx_type & MathCursor::idx()
659 return cursor().idx_;
663 MathCursor::pos_type MathCursor::pos() const
665 return cursor().pos_;
669 void MathCursor::adjust(pos_type from, difference_type diff)
671 if (cursor().pos_ > from)
672 cursor().pos_ += diff;
673 if (Anchor_.back().pos_ > from)
674 Anchor_.back().pos_ += diff;
675 // just to be on the safe side
676 // theoretically unecessary
681 MathCursor::pos_type & MathCursor::pos()
683 return cursor().pos_;
687 bool MathCursor::inMacroMode() const
691 MathUnknownInset const * p = prevAtom()->asUnknownInset();
692 return p && !p->final();
696 MathUnknownInset * MathCursor::activeMacro()
698 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
702 MathUnknownInset const * MathCursor::activeMacro() const
704 return inMacroMode() ? prevAtom()->asUnknownInset() : 0;
708 bool MathCursor::inMacroArgMode() const
710 return pos() > 0 && prevAtom()->getChar() == '#';
714 bool MathCursor::selection() const
720 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
722 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
723 MathGridInset * p = Cursor_[i].par_->asGridInset();
725 idx = Cursor_[i].idx_;
733 void MathCursor::popToHere(MathInset const * p)
735 while (depth() && Cursor_.back().par_ != p)
740 void MathCursor::popToEnclosingGrid()
742 while (depth() && !Cursor_.back().par_->asGridInset())
747 void MathCursor::popToEnclosingHull()
749 while (depth() && !Cursor_.back().par_->asHullInset())
754 void MathCursor::pullArg()
757 MathArray a = array();
760 array().insert(pos(), a);
763 formula()->mutateToText();
768 void MathCursor::touch()
770 MathIterator::const_iterator it = Cursor_.begin();
771 MathIterator::const_iterator et = Cursor_.end();
772 for ( ; it != et; ++it)
777 void MathCursor::normalize()
779 if (idx() >= par()->nargs()) {
780 lyxerr << "this should not really happen - 1: "
781 << idx() << ' ' << par()->nargs()
782 << " in: " << par() << endl;
785 idx() = min(idx(), par()->nargs() - 1);
787 if (pos() > size()) {
788 lyxerr << "this should not really happen - 2: "
789 << pos() << ' ' << size() << " in idx: " << idx()
791 WriteStream wi(lyxerr, false, true);
796 pos() = min(pos(), size());
800 MathCursor::size_type MathCursor::size() const
802 return array().size();
806 bool MathCursor::hasPrevAtom() const
812 bool MathCursor::hasNextAtom() const
814 return pos() < size();
818 MathAtom const & MathCursor::prevAtom() const
820 lyx::Assert(pos() > 0);
821 return array()[pos() - 1];
825 MathAtom & MathCursor::prevAtom()
827 lyx::Assert(pos() > 0);
828 return array()[pos() - 1];
832 MathAtom const & MathCursor::nextAtom() const
834 lyx::Assert(pos() < size());
835 return array()[pos()];
839 MathAtom & MathCursor::nextAtom()
841 lyx::Assert(pos() < size());
842 return array()[pos()];
846 MathArray & MathCursor::array() const
848 static MathArray dummy;
850 if (idx() >= par()->nargs()) {
851 lyxerr << "############ idx_ " << idx() << " not valid\n";
856 lyxerr << "############ depth() == 0 not valid\n";
860 return cursor().cell();
864 void MathCursor::idxNext()
866 par()->idxNext(idx(), pos());
870 void MathCursor::idxPrev()
872 par()->idxPrev(idx(), pos());
876 char MathCursor::valign() const
879 MathGridInset * p = enclosingGrid(idx);
880 return p ? p->valign() : '\0';
884 char MathCursor::halign() const
887 MathGridInset * p = enclosingGrid(idx);
888 return p ? p->halign(idx % p->ncols()) : '\0';
892 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
894 MathCursorPos anc = normalAnchor();
895 if (anc < cursor()) {
905 MathCursorPos & MathCursor::cursor()
907 lyx::Assert(depth());
908 return Cursor_.back();
912 MathCursorPos const & MathCursor::cursor() const
914 lyx::Assert(depth());
915 return Cursor_.back();
919 bool MathCursor::goUpDown(bool up)
921 // Be warned: The 'logic' implemented in this function is highly fragile.
922 // A distance of one pixel or a '<' vs '<=' _really_ matters.
923 // So fiddle around with it only if you know what you are doing!
928 // check if we had something else in mind, if not, this is the future goal
934 // try neigbouring script insets
937 MathScriptInset const * p = prevAtom()->asScriptInset();
938 if (p && p->has(up)) {
941 idx() = up; // the superscript has index 1
943 ///lyxerr << "updown: handled by scriptinset to the left\n";
950 MathScriptInset const * p = nextAtom()->asScriptInset();
951 if (p && p->has(up)) {
955 ///lyxerr << "updown: handled by scriptinset to the right\n";
961 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
966 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
967 // lyxerr << "updown: handled by brute find in the same cell\n";
971 // try to find an inset that knows better then we
973 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
975 if (par()->idxUpDown(idx(), pos(), up, targetx_)) {
976 // try to find best position within this inset
982 // no such inset found, just take something "above"
983 ///lyxerr << "updown: handled by strange case\n";
989 up ? formula()->ylow() : yo + 4,
990 up ? yo - 4 : formula()->yhigh()
993 // any improvement so far?
996 if (up ? ynew < yo : ynew > yo)
1002 bool MathCursor::bruteFind
1003 (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1005 MathIterator best_cursor;
1006 double best_dist = 1e10;
1008 MathIterator it = ibegin(formula()->par().nucleus());
1009 MathIterator et = iend(formula()->par().nucleus());
1011 // avoid invalid nesting when selecting
1012 if (!selection_ || positionable(it, Anchor_)) {
1014 it.back().getPos(xo, yo);
1015 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1016 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1017 // '<=' in order to take the last possible position
1018 // this is important for clicking behind \sum in e.g. '\sum_i a'
1019 if (d <= best_dist) {
1031 if (best_dist < 1e10)
1032 Cursor_ = best_cursor;
1033 return best_dist < 1e10;
1037 void MathCursor::bruteFind2(int x, int y)
1039 double best_dist = 1e10;
1041 MathIterator it = Cursor_;
1042 it.back().setPos(0);
1043 MathIterator et = Cursor_;
1044 et.back().setPos(it.cell().size());
1047 it.back().getPos(xo, yo);
1048 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1049 // '<=' in order to take the last possible position
1050 // this is important for clicking behind \sum in e.g. '\sum_i a'
1051 if (d <= best_dist) {
1062 bool MathCursor::idxLineLast()
1064 idx() -= idx() % par()->ncols();
1065 idx() += par()->ncols() - 1;
1070 bool MathCursor::idxLeft()
1072 return par()->idxLeft(idx(), pos());
1076 bool MathCursor::idxRight()
1078 return par()->idxRight(idx(), pos());
1082 bool MathCursor::script(bool up)
1084 // Hack to get \\^ and \\_ working
1085 if (inMacroMode() && macroName() == "\\") {
1087 niceInsert(createMathInset("mathcircumflex"));
1094 string safe = grabAndEraseSelection();
1096 // we are in a nucleus of a script inset, move to _our_ script
1097 par()->asScriptInset()->ensure(up);
1100 } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1101 prevAtom().nucleus()->asScriptInset()->ensure(up);
1102 pushRight(prevAtom());
1105 } else if (hasPrevAtom()) {
1107 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1108 pushLeft(nextAtom());
1112 plainInsert(MathAtom(new MathScriptInset(up)));
1113 prevAtom().nucleus()->asScriptInset()->ensure(up);
1114 pushRight(prevAtom());
1124 bool MathCursor::interpret(char c)
1126 //lyxerr << "interpret 2: '" << c << "'\n";
1127 targetx_ = -1; // "no target"
1128 if (inMacroArgMode()) {
1132 MathMacroTemplate const * p = formula()->par()->asMacroTemplate();
1133 if (p && 1 <= n && n <= p->numargs())
1134 insert(MathAtom(new MathMacroArgument(c - '0')));
1136 insert(createMathInset("#"));
1137 interpret(c); // try again
1143 if (inMacroMode()) {
1144 string name = macroName();
1145 //lyxerr << "interpret name: '" << name << "'\n";
1148 activeMacro()->setName(activeMacro()->name() + c);
1152 // handle 'special char' macros
1157 if (currentMode() == MathInset::TEXT_MODE)
1158 niceInsert(createMathInset("textbackslash"));
1160 niceInsert(createMathInset("backslash"));
1161 } else if (c == '{') {
1162 niceInsert(MathAtom(new MathBraceInset));
1164 niceInsert(createMathInset(string(1, c)));
1169 // leave macro mode and try again if necessary
1172 niceInsert(MathAtom(new MathBraceInset));
1178 // This is annoying as one has to press <space> far too often.
1182 // leave autocorrect mode if necessary
1183 if (autocorrect_ && c == ' ') {
1184 autocorrect_ = false;
1189 // just clear selection on pressing the space bar
1190 if (selection_ && c == ' ') {
1198 //lyxerr << "starting with macro\n";
1199 insert(MathAtom(new MathUnknownInset("\\", false)));
1204 if (currentMode() == MathInset::TEXT_MODE)
1210 if (currentMode() == MathInset::TEXT_MODE) {
1211 // insert spaces in text mode,
1212 // but suppress direct insertion of two spaces in a row
1213 // the still allows typing '<space>a<space>' and deleting the 'a', but
1214 // it is better than nothing...
1215 if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1219 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1220 prevAtom().nucleus()->asSpaceInset()->incSpace();
1225 // if are at the very end, leave the formula
1226 return pos() != size();
1234 if (c == '{' || c == '}') {
1235 niceInsert(createMathInset(string(1, c)));
1240 insert(createMathInset("$"));
1245 niceInsert(MathAtom(new MathCommentInset));
1249 // try auto-correction
1250 //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1253 // no special circumstances, so insert the character without any fuss
1255 autocorrect_ = true;
1260 void MathCursor::setSelection(MathIterator const & where, size_type n)
1269 void MathCursor::insetToggle()
1271 if (hasNextAtom()) {
1272 // toggle previous inset ...
1273 nextAtom().nucleus()->lock(!nextAtom()->lock());
1274 } else if (popLeft() && hasNextAtom()) {
1275 // ... or enclosing inset if we are in the last inset position
1276 nextAtom().nucleus()->lock(!nextAtom()->lock());
1282 string MathCursor::info() const
1285 os << "Math editor mode. ";
1286 for (int i = 0, n = depth(); i < n; ++i) {
1287 Cursor_[i].par_->infoize(os);
1291 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1292 prevAtom()->infoize(os);
1294 return STRCONV(os.str());
1298 unsigned MathCursor::depth() const
1300 return Cursor_.size();
1308 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1309 MathInset::row_type & r1, MathInset::row_type & r2,
1310 MathInset::col_type & c1, MathInset::col_type & c2)
1312 MathInset * p = i1.par_;
1313 c1 = p->col(i1.idx_);
1314 c2 = p->col(i2.idx_);
1317 r1 = p->row(i1.idx_);
1318 r2 = p->row(i2.idx_);
1326 string MathCursor::grabSelection() const
1333 getSelection(i1, i2);
1335 if (i1.idx_ == i2.idx_) {
1336 MathArray::const_iterator it = i1.cell().begin();
1337 return asString(MathArray(it + i1.pos_, it + i2.pos_));
1342 region(i1, i2, r1, r2, c1, c2);
1345 for (row_type row = r1; row <= r2; ++row) {
1348 for (col_type col = c1; col <= c2; ++col) {
1351 data += asString(i1.par_->cell(i1.par_->index(row, col)));
1358 void MathCursor::eraseSelection()
1362 getSelection(i1, i2);
1363 if (i1.idx_ == i2.idx_)
1364 i1.cell().erase(i1.pos_, i2.pos_);
1366 MathInset * p = i1.par_;
1369 region(i1, i2, r1, r2, c1, c2);
1370 for (row_type row = r1; row <= r2; ++row)
1371 for (col_type col = c1; col <= c2; ++col)
1372 p->cell(p->index(row, col)).clear();
1378 string MathCursor::grabAndEraseSelection()
1382 string res = grabSelection();
1389 MathCursorPos MathCursor::normalAnchor() const
1391 if (Anchor_.size() < depth()) {
1393 lyxerr << "unusual Anchor size\n";
1395 //lyx::Assert(Anchor_.size() >= cursor.depth());
1396 // use Anchor on the same level as Cursor
1397 MathCursorPos normal = Anchor_[depth() - 1];
1398 if (depth() < Anchor_.size() && !(normal < cursor())) {
1399 // anchor is behind cursor -> move anchor behind the inset
1406 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1408 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1409 MathCursorPos & pos = Cursor_[i];
1410 MathInset::result_type
1411 res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1412 if (res != MathInset::UNDISPATCHED) {
1413 if (res == MathInset::DISPATCHED_POP) {
1414 Cursor_.shrink(i + 1);
1420 return MathInset::UNDISPATCHED;
1424 MathInset::mode_type MathCursor::currentMode() const
1426 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1427 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1428 if (res != MathInset::UNDECIDED_MODE)
1431 return MathInset::UNDECIDED_MODE;
1435 void MathCursor::handleFont(string const & font)
1440 safe = grabAndEraseSelection();
1443 if (array().size()) {
1444 // something left in the cell
1446 // cursor in first position
1448 } else if (pos() == array().size()) {
1449 // cursor in last position
1452 // cursor in between. split cell
1453 MathArray::iterator bt = array().begin();
1454 MathAtom at = createMathInset(font);
1455 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1456 cursor().cell().erase(bt, bt + pos());
1461 // nothing left in the cell
1469 void releaseMathCursor(BufferView * bv)
1472 InsetFormulaBase * f = mathcursor->formula();
1473 f->hideInsetCursor(bv);