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_gridinset.h"
39 #include "math_iterator.h"
40 #include "math_macroarg.h"
41 #include "math_macrotemplate.h"
42 #include "math_mathmlstream.h"
43 #include "math_scriptinset.h"
44 #include "math_spaceinset.h"
45 #include "math_support.h"
46 #include "math_unknowninset.h"
58 using std::ostringstream;
62 // matheds own cut buffer
66 MathCursor::MathCursor(InsetFormulaBase * formula, bool front)
67 : formula_(formula), autocorrect_(false), selection_(false)
69 front ? first() : last();
74 MathCursor::~MathCursor()
76 // ensure that 'notifyCursorLeave' is called
82 void MathCursor::push(MathAtom & t)
84 Cursor_.push_back(MathCursorPos(t.nucleus()));
88 void MathCursor::pushLeft(MathAtom & t)
90 //lyxerr << "Entering atom " << t << " left\n";
92 t->idxFirst(idx(), pos());
96 void MathCursor::pushRight(MathAtom & t)
98 //lyxerr << "Entering atom " << t << " right\n";
101 t->idxLast(idx(), pos());
105 bool MathCursor::popLeft()
107 //cerr << "Leaving atom to the left\n";
110 par()->notifyCursorLeaves();
113 par()->notifyCursorLeaves();
119 bool MathCursor::popRight()
121 //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " right\n";
124 par()->notifyCursorLeaves();
127 par()->notifyCursorLeaves();
136 void MathCursor::dump(char const * what) const
138 lyxerr << "MC: " << what << "\n";
139 lyxerr << " Cursor: " << depth() << "\n";
140 for (unsigned i = 0; i < depth(); ++i)
141 lyxerr << " i: " << i << " " << Cursor_[i] << "\n";
142 lyxerr << " Anchor: " << Anchor_.size() << "\n";
143 for (unsigned i = 0; i < Anchor_.size(); ++i)
144 lyxerr << " i: " << i << " " << Anchor_[i] << "\n";
145 lyxerr << " sel: " << selection_ << "\n";
148 void MathCursor::dump(char const *) const {}
152 bool MathCursor::isInside(MathInset const * p) const
154 for (unsigned i = 0; i < depth(); ++i)
155 if (Cursor_[i].par_ == p)
161 bool MathCursor::openable(MathAtom const & t, bool sel) const
170 // we can't move into anything new during selection
171 if (depth() == Anchor_.size())
173 if (t.operator->() != Anchor_[depth()].par_)
180 bool MathCursor::inNucleus() const
182 return par()->asScriptInset() && idx() == 2;
186 bool MathCursor::posLeft()
195 bool MathCursor::posRight()
204 bool MathCursor::left(bool sel)
207 autocorrect_ = false;
208 targetx_ = -1; // "no target"
215 if (hasPrevAtom() && openable(prevAtom(), sel)) {
216 pushRight(prevAtom());
220 return posLeft() || idxLeft() || popLeft() || selection_;
224 bool MathCursor::right(bool sel)
227 autocorrect_ = false;
228 targetx_ = -1; // "no target"
235 if (hasNextAtom() && openable(nextAtom(), sel)) {
236 pushLeft(nextAtom());
240 return posRight() || idxRight() || popRight() || selection_;
244 void MathCursor::first()
247 push(formula_->par());
248 par()->idxFirst(idx(), pos());
252 void MathCursor::last()
255 push(formula_->par());
256 par()->idxLast(idx(), pos());
261 (MathIterator const & cursor, MathIterator const & anchor)
263 // avoid deeper nested insets when selecting
264 if (cursor.size() > anchor.size())
267 // anchor might be deeper, should have same path then
268 for (MathIterator::size_type i = 0; i < cursor.size(); ++i)
269 if (cursor[i].par_ != anchor[i].par_)
272 // position should be ok.
277 void MathCursor::setPos(int x, int y)
280 bool res = bruteFind(x, y,
281 formula()->xlow(), formula()->xhigh(),
282 formula()->ylow(), formula()->yhigh());
284 // this can happen on creation of "math-display"
288 targetx_ = -1; // "no target"
294 bool MathCursor::home(bool sel)
297 autocorrect_ = false;
300 if (!par()->idxHome(idx(), pos()))
303 targetx_ = -1; // "no target"
308 bool MathCursor::end(bool sel)
311 autocorrect_ = false;
314 if (!par()->idxEnd(idx(), pos()))
317 targetx_ = -1; // "no target"
322 void MathCursor::plainErase()
324 array().erase(pos());
328 void MathCursor::markInsert()
330 //lyxerr << "inserting mark\n";
331 array().insert(pos(), MathAtom(new MathCharInset(0)));
335 void MathCursor::markErase()
337 //lyxerr << "deleting mark\n";
338 array().erase(pos());
342 void MathCursor::plainInsert(MathAtom const & t)
345 array().insert(pos(), t);
350 void MathCursor::insert(string const & str)
352 //lyxerr << "inserting '" << str << "'\n";
354 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
355 plainInsert(MathAtom(new MathCharInset(*it)));
359 void MathCursor::insert(char c)
361 //lyxerr << "inserting '" << c << "'\n";
363 plainInsert(MathAtom(new MathCharInset(c)));
367 void MathCursor::insert(MathAtom const & t)
375 void MathCursor::niceInsert(string const & t)
377 MathArray ar = asArray(t);
385 void MathCursor::niceInsert(MathAtom const & t)
388 string safe = grabAndEraseSelection();
390 // enter the new inset and move the contents of the selection if possible
393 pushLeft(nextAtom());
399 void MathCursor::insert(MathArray const & ar)
404 array().insert(pos(), ar);
409 void MathCursor::paste(string const & data)
411 dispatch(FuncRequest(LFUN_PASTE, data));
415 void MathCursor::backspace()
417 autocorrect_ = false;
429 MathUnknownInset * p = activeMacro();
430 if (p->name().size() > 1) {
431 p->setName(p->name().substr(0, p->name().size() - 1));
441 void MathCursor::erase()
443 autocorrect_ = false;
452 // delete empty cells if possible
454 if (par()->idxDelete(idx()))
457 // old behaviour when in last position of cell
458 if (pos() == size()) {
459 par()->idxGlue(idx());
467 bool MathCursor::up(bool sel)
472 MathIterator save = Cursor_;
476 autocorrect_ = false;
481 bool MathCursor::down(bool sel)
486 MathIterator save = Cursor_;
490 autocorrect_ = false;
495 void MathCursor::macroModeClose()
499 MathUnknownInset * p = activeMacro();
501 string s = p->name();
503 array().erase(pos());
505 // do nothing if the macro name is empty
509 string name = s.substr(1);
511 // prevent entering of recursive macros
512 if (formula()->lyxCode() == Inset::MATHMACRO_CODE
513 && formula()->getInsetName() == name)
514 lyxerr << "can't enter recursive macro\n";
516 niceInsert(createMathInset(name));
520 string MathCursor::macroName() const
522 return inMacroMode() ? activeMacro()->name() : string();
526 void MathCursor::selClear()
533 void MathCursor::selCopy()
537 theCutBuffer = grabSelection();
540 theCutBuffer.erase();
545 void MathCursor::selCut()
548 theCutBuffer = grabAndEraseSelection();
552 void MathCursor::selDel()
562 void MathCursor::selPaste()
572 void MathCursor::selHandle(bool sel)
574 if (sel == selection_)
582 void MathCursor::selStart()
592 void MathCursor::selClearOrDel()
594 if (lyxrc.auto_region_delete)
601 void MathCursor::drawSelection(MathPainterInfo & pi) const
607 getSelection(i1, i2);
608 i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
612 void MathCursor::handleNest(MathAtom const & a)
615 at.nucleus()->cell(0) = asArray(grabAndEraseSelection());
617 pushRight(prevAtom());
621 void MathCursor::getPos(int & x, int & y) const
623 par()->getPos(idx(), pos(), x, y);
627 int MathCursor::targetX() const
637 MathInset * MathCursor::par() const
639 return cursor().par_;
643 InsetFormulaBase * MathCursor::formula() const
649 MathCursor::idx_type MathCursor::idx() const
651 return cursor().idx_;
655 MathCursor::idx_type & MathCursor::idx()
657 return cursor().idx_;
661 MathCursor::pos_type MathCursor::pos() const
663 return cursor().pos_;
667 MathCursor::pos_type & MathCursor::pos()
669 return cursor().pos_;
673 bool MathCursor::inMacroMode() const
677 MathUnknownInset const * p = prevAtom()->asUnknownInset();
678 return p && !p->final();
682 MathUnknownInset * MathCursor::activeMacro()
684 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
688 MathUnknownInset const * MathCursor::activeMacro() const
690 return inMacroMode() ? prevAtom()->asUnknownInset() : 0;
694 bool MathCursor::inMacroArgMode() const
696 return pos() > 0 && prevAtom()->getChar() == '#';
700 bool MathCursor::selection() const
706 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
708 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
709 MathGridInset * p = Cursor_[i].par_->asGridInset();
711 idx = Cursor_[i].idx_;
719 void MathCursor::popToHere(MathInset const * p)
721 while (depth() && Cursor_.back().par_ != p)
726 void MathCursor::popToEnclosingGrid()
728 while (depth() && !Cursor_.back().par_->asGridInset())
733 void MathCursor::popToEnclosingHull()
735 while (depth() && !Cursor_.back().par_->asHullInset())
740 void MathCursor::pullArg()
743 MathArray a = array();
746 array().insert(pos(), a);
749 formula()->mutateToText();
754 void MathCursor::touch()
756 MathIterator::const_iterator it = Cursor_.begin();
757 MathIterator::const_iterator et = Cursor_.end();
758 for ( ; it != et; ++it)
763 void MathCursor::normalize()
765 if (idx() >= par()->nargs()) {
766 lyxerr << "this should not really happen - 1: "
767 << idx() << " " << par()->nargs() << " in: " << par() << "\n";
770 idx() = min(idx(), par()->nargs() - 1);
772 if (pos() > size()) {
773 lyxerr << "this should not really happen - 2: "
774 << pos() << " " << size() << " in idx: " << idx()
776 WriteStream wi(lyxerr, false, true);
781 pos() = min(pos(), size());
783 // remove empty scripts if possible
785 for (pos_type i = 0; i < size(); ++i) {
786 MathScriptInset * p = array()[i].nucleus()->asScriptInset();
788 p->removeEmptyScripts();
789 if (!p->hasUp() && !p->hasDown() && p->nuc().size() == 1)
790 array()[i] = p->nuc()[0];
795 // fix again position
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 os.str().c_str(); // .c_str() needed for lyxstring
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);
1337 region(i1, i2, r1, r2, c1, c2);
1340 for (row_type row = r1; row <= r2; ++row) {
1343 for (col_type col = c1; col <= c2; ++col) {
1346 data += asString(i1.par_->cell(i1.par_->index(row, col)));
1353 void MathCursor::eraseSelection()
1357 getSelection(i1, i2);
1358 if (i1.idx_ == i2.idx_)
1359 i1.cell().erase(i1.pos_, i2.pos_);
1361 MathInset * p = i1.par_;
1364 region(i1, i2, r1, r2, c1, c2);
1365 for (row_type row = r1; row <= r2; ++row)
1366 for (col_type col = c1; col <= c2; ++col)
1367 p->cell(p->index(row, col)).clear();
1373 string MathCursor::grabAndEraseSelection()
1377 string res = grabSelection();
1384 MathCursorPos MathCursor::normalAnchor() const
1386 if (Anchor_.size() < depth()) {
1388 lyxerr << "unusual Anchor size\n";
1390 //lyx::Assert(Anchor_.size() >= cursor.depth());
1391 // use Anchor on the same level as Cursor
1392 MathCursorPos normal = Anchor_[depth() - 1];
1393 if (depth() < Anchor_.size() && !(normal < cursor())) {
1394 // anchor is behind cursor -> move anchor behind the inset
1401 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1403 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1404 MathCursorPos & pos = Cursor_[i];
1405 MathInset::result_type
1406 res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1407 if (res != MathInset::UNDISPATCHED) {
1408 if (res == MathInset::DISPATCHED_POP) {
1409 Cursor_.shrink(i + 1);
1415 return MathInset::UNDISPATCHED;
1419 MathInset::mode_type MathCursor::currentMode() const
1421 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1422 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1423 if (res != MathInset::UNDECIDED_MODE)
1426 return MathInset::UNDECIDED_MODE;
1430 void releaseMathCursor(BufferView * bv)
1434 mathcursor->formula()->hideInsetCursor(bv);