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;
430 MathUnknownInset * p = activeMacro();
431 if (p->name().size() > 1) {
432 p->setName(p->name().substr(0, p->name().size() - 1));
442 void MathCursor::erase()
444 autocorrect_ = false;
453 // delete empty cells if possible
455 if (par()->idxDelete(idx()))
458 // old behaviour when in last position of cell
459 if (pos() == size()) {
460 par()->idxGlue(idx());
468 bool MathCursor::up(bool sel)
473 MathIterator save = Cursor_;
477 autocorrect_ = false;
482 bool MathCursor::down(bool sel)
487 MathIterator save = Cursor_;
491 autocorrect_ = false;
496 void MathCursor::macroModeClose()
500 MathUnknownInset * p = activeMacro();
502 string s = p->name();
504 array().erase(pos());
506 // do nothing if the macro name is empty
510 string name = s.substr(1);
512 // prevent entering of recursive macros
513 if (formula()->lyxCode() == Inset::MATHMACRO_CODE
514 && formula()->getInsetName() == name)
515 lyxerr << "can't enter recursive macro\n";
517 niceInsert(createMathInset(name));
521 string MathCursor::macroName() const
523 return inMacroMode() ? activeMacro()->name() : string();
527 void MathCursor::selClear()
534 void MathCursor::selCopy()
538 theCutBuffer = grabSelection();
541 theCutBuffer.erase();
546 void MathCursor::selCut()
549 theCutBuffer = grabAndEraseSelection();
553 void MathCursor::selDel()
563 void MathCursor::selPaste()
573 void MathCursor::selHandle(bool sel)
575 if (sel == selection_)
583 void MathCursor::selStart()
593 void MathCursor::selClearOrDel()
595 if (lyxrc.auto_region_delete)
602 void MathCursor::drawSelection(MathPainterInfo & pi) const
608 getSelection(i1, i2);
609 i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
613 void MathCursor::handleNest(MathAtom const & a)
616 at.nucleus()->cell(0) = asArray(grabAndEraseSelection());
618 pushRight(prevAtom());
622 void MathCursor::getPos(int & x, int & y) const
624 par()->getPos(idx(), pos(), x, y);
628 int MathCursor::targetX() const
638 MathInset * MathCursor::par() const
640 return cursor().par_;
644 InsetFormulaBase * MathCursor::formula() const
650 MathCursor::idx_type MathCursor::idx() const
652 return cursor().idx_;
656 MathCursor::idx_type & MathCursor::idx()
658 return cursor().idx_;
662 MathCursor::pos_type MathCursor::pos() const
664 return cursor().pos_;
668 MathCursor::pos_type & MathCursor::pos()
670 return cursor().pos_;
674 bool MathCursor::inMacroMode() const
678 MathUnknownInset const * p = prevAtom()->asUnknownInset();
679 return p && !p->final();
683 MathUnknownInset * MathCursor::activeMacro()
685 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
689 MathUnknownInset const * MathCursor::activeMacro() const
691 return inMacroMode() ? prevAtom()->asUnknownInset() : 0;
695 bool MathCursor::inMacroArgMode() const
697 return pos() > 0 && prevAtom()->getChar() == '#';
701 bool MathCursor::selection() const
707 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
709 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
710 MathGridInset * p = Cursor_[i].par_->asGridInset();
712 idx = Cursor_[i].idx_;
720 void MathCursor::popToHere(MathInset const * p)
722 while (depth() && Cursor_.back().par_ != p)
727 void MathCursor::popToEnclosingGrid()
729 while (depth() && !Cursor_.back().par_->asGridInset())
734 void MathCursor::popToEnclosingHull()
736 while (depth() && !Cursor_.back().par_->asHullInset())
741 void MathCursor::pullArg()
744 MathArray a = array();
747 array().insert(pos(), a);
750 formula()->mutateToText();
755 void MathCursor::touch()
757 MathIterator::const_iterator it = Cursor_.begin();
758 MathIterator::const_iterator et = Cursor_.end();
759 for ( ; it != et; ++it)
764 void MathCursor::normalize()
766 if (idx() >= par()->nargs()) {
767 lyxerr << "this should not really happen - 1: "
768 << idx() << " " << par()->nargs() << " in: " << par() << "\n";
771 idx() = min(idx(), par()->nargs() - 1);
773 if (pos() > size()) {
774 lyxerr << "this should not really happen - 2: "
775 << pos() << " " << size() << " in idx: " << idx()
777 WriteStream wi(lyxerr, false, true);
782 pos() = min(pos(), size());
784 // remove empty scripts if possible
786 for (pos_type i = 0; i < size(); ++i) {
787 MathScriptInset * p = array()[i].nucleus()->asScriptInset();
789 p->removeEmptyScripts();
790 if (!p->hasUp() && !p->hasDown() && p->nuc().size() == 1)
791 array()[i] = p->nuc()[0];
796 // fix again position
797 pos() = min(pos(), size());
801 MathCursor::size_type MathCursor::size() const
803 return array().size();
807 bool MathCursor::hasPrevAtom() const
813 bool MathCursor::hasNextAtom() const
815 return pos() < size();
819 MathAtom const & MathCursor::prevAtom() const
821 lyx::Assert(pos() > 0);
822 return array()[pos() - 1];
826 MathAtom & MathCursor::prevAtom()
828 lyx::Assert(pos() > 0);
829 return array()[pos() - 1];
833 MathAtom const & MathCursor::nextAtom() const
835 lyx::Assert(pos() < size());
836 return array()[pos()];
840 MathAtom & MathCursor::nextAtom()
842 lyx::Assert(pos() < size());
843 return array()[pos()];
847 MathArray & MathCursor::array() const
849 static MathArray dummy;
851 if (idx() >= par()->nargs()) {
852 lyxerr << "############ idx_ " << idx() << " not valid\n";
857 lyxerr << "############ depth() == 0 not valid\n";
861 return cursor().cell();
865 void MathCursor::idxNext()
867 par()->idxNext(idx(), pos());
871 void MathCursor::idxPrev()
873 par()->idxPrev(idx(), pos());
877 char MathCursor::valign() const
880 MathGridInset * p = enclosingGrid(idx);
881 return p ? p->valign() : '\0';
885 char MathCursor::halign() const
888 MathGridInset * p = enclosingGrid(idx);
889 return p ? p->halign(idx % p->ncols()) : '\0';
893 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
895 MathCursorPos anc = normalAnchor();
896 if (anc < cursor()) {
906 MathCursorPos & MathCursor::cursor()
908 lyx::Assert(depth());
909 return Cursor_.back();
913 MathCursorPos const & MathCursor::cursor() const
915 lyx::Assert(depth());
916 return Cursor_.back();
920 bool MathCursor::goUpDown(bool up)
922 // Be warned: The 'logic' implemented in this function is highly fragile.
923 // A distance of one pixel or a '<' vs '<=' _really_ matters.
924 // So fiddle around with it only if you know what you are doing!
929 // check if we had something else in mind, if not, this is the future goal
935 // try neigbouring script insets
938 MathScriptInset const * p = prevAtom()->asScriptInset();
939 if (p && p->has(up)) {
942 idx() = up; // the superscript has index 1
944 ///lyxerr << "updown: handled by scriptinset to the left\n";
951 MathScriptInset const * p = nextAtom()->asScriptInset();
952 if (p && p->has(up)) {
956 ///lyxerr << "updown: handled by scriptinset to the right\n";
962 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
967 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
968 // lyxerr << "updown: handled by brute find in the same cell\n";
972 // try to find an inset that knows better then we
974 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
976 if (par()->idxUpDown(idx(), pos(), up, targetx_)) {
977 // try to find best position within this inset
983 // no such inset found, just take something "above"
984 ///lyxerr << "updown: handled by strange case\n";
990 up ? formula()->ylow() : yo + 4,
991 up ? yo - 4 : formula()->yhigh()
994 // any improvement so far?
997 if (up ? ynew < yo : ynew > yo)
1003 bool MathCursor::bruteFind
1004 (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1006 MathIterator best_cursor;
1007 double best_dist = 1e10;
1009 MathIterator it = ibegin(formula()->par().nucleus());
1010 MathIterator et = iend(formula()->par().nucleus());
1012 // avoid invalid nesting when selecting
1013 if (!selection_ || positionable(it, Anchor_)) {
1015 it.back().getPos(xo, yo);
1016 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1017 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1018 // '<=' in order to take the last possible position
1019 // this is important for clicking behind \sum in e.g. '\sum_i a'
1020 if (d <= best_dist) {
1032 if (best_dist < 1e10)
1033 Cursor_ = best_cursor;
1034 return best_dist < 1e10;
1038 void MathCursor::bruteFind2(int x, int y)
1040 double best_dist = 1e10;
1042 MathIterator it = Cursor_;
1043 it.back().setPos(0);
1044 MathIterator et = Cursor_;
1045 et.back().setPos(it.cell().size());
1048 it.back().getPos(xo, yo);
1049 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1050 // '<=' in order to take the last possible position
1051 // this is important for clicking behind \sum in e.g. '\sum_i a'
1052 if (d <= best_dist) {
1063 bool MathCursor::idxLineLast()
1065 idx() -= idx() % par()->ncols();
1066 idx() += par()->ncols() - 1;
1071 bool MathCursor::idxLeft()
1073 return par()->idxLeft(idx(), pos());
1077 bool MathCursor::idxRight()
1079 return par()->idxRight(idx(), pos());
1083 bool MathCursor::script(bool up)
1085 // Hack to get \\^ and \\_ working
1086 if (inMacroMode() && macroName() == "\\") {
1088 niceInsert(createMathInset("mathcircumflex"));
1095 string safe = grabAndEraseSelection();
1097 // we are in a nucleus of a script inset, move to _our_ script
1098 par()->asScriptInset()->ensure(up);
1101 } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1102 prevAtom().nucleus()->asScriptInset()->ensure(up);
1103 pushRight(prevAtom());
1106 } else if (hasPrevAtom()) {
1108 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1109 pushLeft(nextAtom());
1113 plainInsert(MathAtom(new MathScriptInset(up)));
1114 prevAtom().nucleus()->asScriptInset()->ensure(up);
1115 pushRight(prevAtom());
1125 bool MathCursor::interpret(char c)
1127 //lyxerr << "interpret 2: '" << c << "'\n";
1128 targetx_ = -1; // "no target"
1129 if (inMacroArgMode()) {
1133 MathMacroTemplate const * p = formula()->par()->asMacroTemplate();
1134 if (p && 1 <= n && n <= p->numargs())
1135 insert(MathAtom(new MathMacroArgument(c - '0')));
1137 insert(createMathInset("#"));
1138 interpret(c); // try again
1144 if (inMacroMode()) {
1145 string name = macroName();
1146 //lyxerr << "interpret name: '" << name << "'\n";
1149 activeMacro()->setName(activeMacro()->name() + c);
1153 // handle 'special char' macros
1158 if (currentMode() == MathInset::TEXT_MODE)
1159 niceInsert(createMathInset("textbackslash"));
1161 niceInsert(createMathInset("backslash"));
1162 } else if (c == '{') {
1163 niceInsert(MathAtom(new MathBraceInset));
1165 niceInsert(createMathInset(string(1, c)));
1170 // leave macro mode and try again if necessary
1173 niceInsert(MathAtom(new MathBraceInset));
1179 // This is annoying as one has to press <space> far too often.
1183 // leave autocorrect mode if necessary
1184 if (autocorrect_ && c == ' ') {
1185 autocorrect_ = false;
1190 // just clear selection on pressing the space bar
1191 if (selection_ && c == ' ') {
1199 //lyxerr << "starting with macro\n";
1200 insert(MathAtom(new MathUnknownInset("\\", false)));
1205 if (currentMode() == MathInset::TEXT_MODE)
1211 if (currentMode() == MathInset::TEXT_MODE) {
1212 // insert spaces in text mode,
1213 // but suppress direct insertion of two spaces in a row
1214 // the still allows typing '<space>a<space>' and deleting the 'a', but
1215 // it is better than nothing...
1216 if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1220 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1221 prevAtom().nucleus()->asSpaceInset()->incSpace();
1226 // if are at the very end, leave the formula
1227 return pos() != size();
1235 if (c == '{' || c == '}') {
1236 niceInsert(createMathInset(string(1, c)));
1241 insert(createMathInset("$"));
1246 niceInsert(MathAtom(new MathCommentInset));
1250 // try auto-correction
1251 //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1254 // no special circumstances, so insert the character without any fuss
1256 autocorrect_ = true;
1261 void MathCursor::setSelection(MathIterator const & where, size_type n)
1270 void MathCursor::insetToggle()
1272 if (hasNextAtom()) {
1273 // toggle previous inset ...
1274 nextAtom().nucleus()->lock(!nextAtom()->lock());
1275 } else if (popLeft() && hasNextAtom()) {
1276 // ... or enclosing inset if we are in the last inset position
1277 nextAtom().nucleus()->lock(!nextAtom()->lock());
1283 string MathCursor::info() const
1286 os << "Math editor mode. ";
1287 for (int i = 0, n = depth(); i < n; ++i) {
1288 Cursor_[i].par_->infoize(os);
1292 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1293 prevAtom()->infoize(os);
1295 return os.str().c_str(); // .c_str() needed for lyxstring
1299 unsigned MathCursor::depth() const
1301 return Cursor_.size();
1309 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1310 MathInset::row_type & r1, MathInset::row_type & r2,
1311 MathInset::col_type & c1, MathInset::col_type & c2)
1313 MathInset * p = i1.par_;
1314 c1 = p->col(i1.idx_);
1315 c2 = p->col(i2.idx_);
1318 r1 = p->row(i1.idx_);
1319 r2 = p->row(i2.idx_);
1327 string MathCursor::grabSelection() const
1334 getSelection(i1, i2);
1336 if (i1.idx_ == i2.idx_) {
1337 MathArray::const_iterator it = i1.cell().begin();
1338 return asString(MathArray(it + i1.pos_, it + i2.pos_));
1343 region(i1, i2, r1, r2, c1, c2);
1346 for (row_type row = r1; row <= r2; ++row) {
1349 for (col_type col = c1; col <= c2; ++col) {
1352 data += asString(i1.par_->cell(i1.par_->index(row, col)));
1359 void MathCursor::eraseSelection()
1363 getSelection(i1, i2);
1364 if (i1.idx_ == i2.idx_)
1365 i1.cell().erase(i1.pos_, i2.pos_);
1367 MathInset * p = i1.par_;
1370 region(i1, i2, r1, r2, c1, c2);
1371 for (row_type row = r1; row <= r2; ++row)
1372 for (col_type col = c1; col <= c2; ++col)
1373 p->cell(p->index(row, col)).clear();
1379 string MathCursor::grabAndEraseSelection()
1383 string res = grabSelection();
1390 MathCursorPos MathCursor::normalAnchor() const
1392 if (Anchor_.size() < depth()) {
1394 lyxerr << "unusual Anchor size\n";
1396 //lyx::Assert(Anchor_.size() >= cursor.depth());
1397 // use Anchor on the same level as Cursor
1398 MathCursorPos normal = Anchor_[depth() - 1];
1399 if (depth() < Anchor_.size() && !(normal < cursor())) {
1400 // anchor is behind cursor -> move anchor behind the inset
1407 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1409 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1410 MathCursorPos & pos = Cursor_[i];
1411 MathInset::result_type
1412 res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1413 if (res != MathInset::UNDISPATCHED) {
1414 if (res == MathInset::DISPATCHED_POP) {
1415 Cursor_.shrink(i + 1);
1421 return MathInset::UNDISPATCHED;
1425 MathInset::mode_type MathCursor::currentMode() const
1427 for (int i = Cursor_.size() - 1; i >= 0; --i) {
1428 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1429 if (res != MathInset::UNDECIDED_MODE)
1432 return MathInset::UNDECIDED_MODE;
1436 void releaseMathCursor(BufferView * bv)
1440 mathcursor->formula()->hideInsetCursor(bv);