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)
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 << "\n";
140 lyxerr << " Cursor: " << depth() << "\n";
141 for (unsigned i = 0; i < depth(); ++i)
142 lyxerr << " i: " << i << " " << Cursor_[i] << "\n";
143 lyxerr << " Anchor: " << Anchor_.size() << "\n";
144 for (unsigned i = 0; i < Anchor_.size(); ++i)
145 lyxerr << " i: " << i << " " << Anchor_[i] << "\n";
146 lyxerr << " sel: " << selection_ << "\n";
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() << " in: " << par() << "\n";
784 idx() = min(idx(), par()->nargs() - 1);
786 if (pos() > size()) {
787 lyxerr << "this should not really happen - 2: "
788 << pos() << " " << size() << " in idx: " << idx()
790 WriteStream wi(lyxerr, false, true);
795 pos() = min(pos(), size());
799 MathCursor::size_type MathCursor::size() const
801 return array().size();
805 bool MathCursor::hasPrevAtom() const
811 bool MathCursor::hasNextAtom() const
813 return pos() < size();
817 MathAtom const & MathCursor::prevAtom() const
819 lyx::Assert(pos() > 0);
820 return array()[pos() - 1];
824 MathAtom & MathCursor::prevAtom()
826 lyx::Assert(pos() > 0);
827 return array()[pos() - 1];
831 MathAtom const & MathCursor::nextAtom() const
833 lyx::Assert(pos() < size());
834 return array()[pos()];
838 MathAtom & MathCursor::nextAtom()
840 lyx::Assert(pos() < size());
841 return array()[pos()];
845 MathArray & MathCursor::array() const
847 static MathArray dummy;
849 if (idx() >= par()->nargs()) {
850 lyxerr << "############ idx_ " << idx() << " not valid\n";
855 lyxerr << "############ depth() == 0 not valid\n";
859 return cursor().cell();
863 void MathCursor::idxNext()
865 par()->idxNext(idx(), pos());
869 void MathCursor::idxPrev()
871 par()->idxPrev(idx(), pos());
875 char MathCursor::valign() const
878 MathGridInset * p = enclosingGrid(idx);
879 return p ? p->valign() : '\0';
883 char MathCursor::halign() const
886 MathGridInset * p = enclosingGrid(idx);
887 return p ? p->halign(idx % p->ncols()) : '\0';
891 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
893 MathCursorPos anc = normalAnchor();
894 if (anc < cursor()) {
904 MathCursorPos & MathCursor::cursor()
906 lyx::Assert(depth());
907 return Cursor_.back();
911 MathCursorPos const & MathCursor::cursor() const
913 lyx::Assert(depth());
914 return Cursor_.back();
918 bool MathCursor::goUpDown(bool up)
920 // Be warned: The 'logic' implemented in this function is highly fragile.
921 // A distance of one pixel or a '<' vs '<=' _really_ matters.
922 // So fiddle around with it only if you know what you are doing!
927 // check if we had something else in mind, if not, this is the future goal
933 // try neigbouring script insets
936 MathScriptInset const * p = prevAtom()->asScriptInset();
937 if (p && p->has(up)) {
940 idx() = up; // the superscript has index 1
942 ///lyxerr << "updown: handled by scriptinset to the left\n";
949 MathScriptInset const * p = nextAtom()->asScriptInset();
950 if (p && p->has(up)) {
954 ///lyxerr << "updown: handled by scriptinset to the right\n";
960 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
965 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
966 // lyxerr << "updown: handled by brute find in the same cell\n";
970 // try to find an inset that knows better then we
972 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
974 if (par()->idxUpDown(idx(), pos(), up, targetx_)) {
975 // try to find best position within this inset
981 // no such inset found, just take something "above"
982 ///lyxerr << "updown: handled by strange case\n";
988 up ? formula()->ylow() : yo + 4,
989 up ? yo - 4 : formula()->yhigh()
992 // any improvement so far?
995 if (up ? ynew < yo : ynew > yo)
1001 bool MathCursor::bruteFind
1002 (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1004 MathIterator best_cursor;
1005 double best_dist = 1e10;
1007 MathIterator it = ibegin(formula()->par().nucleus());
1008 MathIterator et = iend(formula()->par().nucleus());
1010 // avoid invalid nesting when selecting
1011 if (!selection_ || positionable(it, Anchor_)) {
1013 it.back().getPos(xo, yo);
1014 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1015 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1016 // '<=' in order to take the last possible position
1017 // this is important for clicking behind \sum in e.g. '\sum_i a'
1018 if (d <= best_dist) {
1030 if (best_dist < 1e10)
1031 Cursor_ = best_cursor;
1032 return best_dist < 1e10;
1036 void MathCursor::bruteFind2(int x, int y)
1038 double best_dist = 1e10;
1040 MathIterator it = Cursor_;
1041 it.back().setPos(0);
1042 MathIterator et = Cursor_;
1043 et.back().setPos(it.cell().size());
1046 it.back().getPos(xo, yo);
1047 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1048 // '<=' in order to take the last possible position
1049 // this is important for clicking behind \sum in e.g. '\sum_i a'
1050 if (d <= best_dist) {
1061 bool MathCursor::idxLineLast()
1063 idx() -= idx() % par()->ncols();
1064 idx() += par()->ncols() - 1;
1069 bool MathCursor::idxLeft()
1071 return par()->idxLeft(idx(), pos());
1075 bool MathCursor::idxRight()
1077 return par()->idxRight(idx(), pos());
1081 bool MathCursor::script(bool up)
1083 // Hack to get \\^ and \\_ working
1084 if (inMacroMode() && macroName() == "\\") {
1086 niceInsert(createMathInset("mathcircumflex"));
1093 string safe = grabAndEraseSelection();
1095 // we are in a nucleus of a script inset, move to _our_ script
1096 par()->asScriptInset()->ensure(up);
1099 } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1100 prevAtom().nucleus()->asScriptInset()->ensure(up);
1101 pushRight(prevAtom());
1104 } else if (hasPrevAtom()) {
1106 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1107 pushLeft(nextAtom());
1111 plainInsert(MathAtom(new MathScriptInset(up)));
1112 prevAtom().nucleus()->asScriptInset()->ensure(up);
1113 pushRight(prevAtom());
1123 bool MathCursor::interpret(char c)
1125 //lyxerr << "interpret 2: '" << c << "'\n";
1126 targetx_ = -1; // "no target"
1127 if (inMacroArgMode()) {
1131 MathMacroTemplate const * p = formula()->par()->asMacroTemplate();
1132 if (p && 1 <= n && n <= p->numargs())
1133 insert(MathAtom(new MathMacroArgument(c - '0')));
1135 insert(createMathInset("#"));
1136 interpret(c); // try again
1142 if (inMacroMode()) {
1143 string name = macroName();
1144 //lyxerr << "interpret name: '" << name << "'\n";
1147 activeMacro()->setName(activeMacro()->name() + c);
1151 // handle 'special char' macros
1156 if (currentMode() == MathInset::TEXT_MODE)
1157 niceInsert(createMathInset("textbackslash"));
1159 niceInsert(createMathInset("backslash"));
1160 } else if (c == '{') {
1161 niceInsert(MathAtom(new MathBraceInset));
1163 niceInsert(createMathInset(string(1, c)));
1168 // leave macro mode and try again if necessary
1171 niceInsert(MathAtom(new MathBraceInset));
1177 // This is annoying as one has to press <space> far too often.
1181 // leave autocorrect mode if necessary
1182 if (autocorrect_ && c == ' ') {
1183 autocorrect_ = false;
1188 // just clear selection on pressing the space bar
1189 if (selection_ && c == ' ') {
1197 //lyxerr << "starting with macro\n";
1198 insert(MathAtom(new MathUnknownInset("\\", false)));
1203 if (currentMode() == MathInset::TEXT_MODE)
1209 if (currentMode() == MathInset::TEXT_MODE) {
1210 // insert spaces in text mode,
1211 // but suppress direct insertion of two spaces in a row
1212 // the still allows typing '<space>a<space>' and deleting the 'a', but
1213 // it is better than nothing...
1214 if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1218 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1219 prevAtom().nucleus()->asSpaceInset()->incSpace();
1224 // if are at the very end, leave the formula
1225 return pos() != size();
1233 if (c == '{' || c == '}') {
1234 niceInsert(createMathInset(string(1, c)));
1239 insert(createMathInset("$"));
1244 niceInsert(MathAtom(new MathCommentInset));
1248 // try auto-correction
1249 //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1252 // no special circumstances, so insert the character without any fuss
1254 autocorrect_ = true;
1259 void MathCursor::setSelection(MathIterator const & where, size_type n)
1268 void MathCursor::insetToggle()
1270 if (hasNextAtom()) {
1271 // toggle previous inset ...
1272 nextAtom().nucleus()->lock(!nextAtom()->lock());
1273 } else if (popLeft() && hasNextAtom()) {
1274 // ... or enclosing inset if we are in the last inset position
1275 nextAtom().nucleus()->lock(!nextAtom()->lock());
1281 string MathCursor::info() const
1284 os << "Math editor mode. ";
1285 for (int i = 0, n = depth(); i < n; ++i) {
1286 Cursor_[i].par_->infoize(os);
1290 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1291 prevAtom()->infoize(os);
1293 return STRCONV(os.str());
1297 unsigned MathCursor::depth() const
1299 return Cursor_.size();
1307 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1308 MathInset::row_type & r1, MathInset::row_type & r2,
1309 MathInset::col_type & c1, MathInset::col_type & c2)
1311 MathInset * p = i1.par_;
1312 c1 = p->col(i1.idx_);
1313 c2 = p->col(i2.idx_);
1316 r1 = p->row(i1.idx_);
1317 r2 = p->row(i2.idx_);
1325 string MathCursor::grabSelection() const
1332 getSelection(i1, i2);
1334 if (i1.idx_ == i2.idx_) {
1335 MathArray::const_iterator it = i1.cell().begin();
1336 return asString(MathArray(it + i1.pos_, it + i2.pos_));
1341 region(i1, i2, r1, r2, c1, c2);
1344 for (row_type row = r1; row <= r2; ++row) {
1347 for (col_type col = c1; col <= c2; ++col) {
1350 data += asString(i1.par_->cell(i1.par_->index(row, col)));
1357 void MathCursor::eraseSelection()
1361 getSelection(i1, i2);
1362 if (i1.idx_ == i2.idx_)
1363 i1.cell().erase(i1.pos_, i2.pos_);
1365 MathInset * p = i1.par_;
1368 region(i1, i2, r1, r2, c1, c2);
1369 for (row_type row = r1; row <= r2; ++row)
1370 for (col_type col = c1; col <= c2; ++col)
1371 p->cell(p->index(row, col)).clear();
1377 string MathCursor::grabAndEraseSelection()
1381 string res = grabSelection();
1388 MathCursorPos MathCursor::normalAnchor() const
1390 if (Anchor_.size() < depth()) {
1392 lyxerr << "unusual Anchor size\n";
1394 //lyx::Assert(Anchor_.size() >= cursor.depth());
1395 // use Anchor on the same level as Cursor
1396 MathCursorPos normal = Anchor_[depth() - 1];
1397 if (depth() < Anchor_.size() && !(normal < cursor())) {
1398 // anchor is behind cursor -> move anchor behind the inset
1405 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1407 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1408 MathCursorPos & pos = Cursor_[i];
1409 MathInset::result_type
1410 res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1411 if (res != MathInset::UNDISPATCHED) {
1412 if (res == MathInset::DISPATCHED_POP) {
1413 Cursor_.shrink(i + 1);
1419 return MathInset::UNDISPATCHED;
1423 MathInset::mode_type MathCursor::currentMode() const
1425 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1426 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1427 if (res != MathInset::UNDECIDED_MODE)
1430 return MathInset::UNDECIDED_MODE;
1434 void MathCursor::handleFont(string const & font)
1439 safe = grabAndEraseSelection();
1442 if (array().size()) {
1443 // something left in the cell
1445 // cursor in first position
1447 } else if (pos() == array().size()) {
1448 // cursor in last position
1451 // cursor in between. split cell
1452 MathArray::iterator bt = array().begin();
1453 MathAtom at = createMathInset(font);
1454 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1455 cursor().cell().erase(bt, bt + pos());
1460 // nothing left in the cell
1468 void releaseMathCursor(BufferView * bv)
1472 mathcursor->formula()->hideInsetCursor(bv);