3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
10 * Full author contact details are available in file CREDITS.
15 #include "BufferView.h"
18 #include "CutAndPaste.h"
20 #include "dispatchresult.h"
22 #include "funcrequest.h"
26 #include "lyxfunc.h" // only for setMessage()
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "pariterator.h"
34 #include "insets/updatableinset.h"
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
38 #include "mathed/math_data.h"
39 #include "mathed/math_support.h"
40 #include "mathed/math_inset.h"
42 #include "support/limited_stack.h"
43 #include "support/std_sstream.h"
45 #include "frontends/LyXView.h"
47 #include <boost/assert.hpp>
54 #ifndef CXX_GLOBAL_CSTD
63 limited_stack<string> theCutBuffer;
68 void region(CursorSlice const & i1, CursorSlice const & i2,
69 LCursor::row_type & r1, LCursor::row_type & r2,
70 LCursor::col_type & c1, LCursor::col_type & c2)
72 InsetBase & p = i1.inset();
86 LCursor::LCursor(BufferView & bv)
87 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
88 selection_(false), mark_(false)
92 void LCursor::reset(InsetBase & inset)
95 push_back(CursorSlice(inset));
96 anchor_ = DocIterator(inset);
103 void LCursor::setCursor(DocIterator const & cur, bool sel)
105 // this (intentionally) does not touch the anchor
106 DocIterator::operator=(cur);
111 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
113 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
115 return DispatchResult();
117 FuncRequest cmd = cmd0;
118 LCursor safe = *this;
120 for ( ; size(); pop()) {
121 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
122 BOOST_ASSERT(pos() <= lastpos());
123 BOOST_ASSERT(idx() <= lastidx());
124 BOOST_ASSERT(par() <= lastpar());
126 // The common case is 'LFUN handled, need update', so make the
127 // LFUN handler's life easier by assuming this as default value.
128 // The handler can reset the update and val flags if necessary.
130 disp_.dispatched(true);
131 inset().dispatch(*this, cmd);
132 if (disp_.dispatched())
135 // it completely to get a 'bomb early' behaviour in case this
136 // object will be used again.
137 if (!disp_.dispatched()) {
138 lyxerr << "RESTORING OLD CURSOR!" << endl;
145 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
147 // This is, of course, a mess. Better create a new doc iterator and use
148 // this in Inset::getStatus. This might require an additional
149 // BufferView * arg, though (which should be avoided)
150 LCursor safe = *this;
152 for ( ; size(); pop()) {
153 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
154 BOOST_ASSERT(pos() <= lastpos());
155 BOOST_ASSERT(idx() <= lastidx());
156 BOOST_ASSERT(par() <= lastpar());
158 // The inset's getStatus() will return 'true' if it made
159 // a definitive decision on whether it want to handle the
160 // request or not. The result of this decision is put into
161 // the 'status' parameter.
162 if (inset().getStatus(*this, cmd, status)) {
172 BufferView & LCursor::bv() const
180 BOOST_ASSERT(size() >= 1);
185 void LCursor::push(InsetBase & p)
187 push_back(CursorSlice(p));
191 void LCursor::pushLeft(InsetBase & p)
193 BOOST_ASSERT(!empty());
194 //lyxerr << "Entering inset " << t << " left" << endl;
200 bool LCursor::popLeft()
202 BOOST_ASSERT(!empty());
203 //lyxerr << "Leaving inset to the left" << endl;
204 inset().notifyCursorLeaves(idx());
212 bool LCursor::popRight()
214 BOOST_ASSERT(!empty());
215 //lyxerr << "Leaving inset to the right" << endl;
216 inset().notifyCursorLeaves(idx());
225 int LCursor::currentMode()
227 BOOST_ASSERT(!empty());
228 for (int i = size() - 1; i >= 0; --i) {
229 int res = operator[](i).inset().currentMode();
230 if (res != InsetBase::UNDECIDED_MODE)
233 return InsetBase::TEXT_MODE;
237 void LCursor::getDim(int & asc, int & des) const
240 BOOST_ASSERT(inset().asMathInset());
241 //inset().asMathInset()->getCursorDim(asc, des);
244 } else if (inTexted()) {
245 Row const & row = textRow();
246 asc = row.baseline();
247 des = row.height() - asc;
249 lyxerr << "should this happen?" << endl;
256 void LCursor::getPos(int & x, int & y) const
261 inset().getCursorPos(back(), x, y);
265 void LCursor::paste(string const & data)
267 dispatch(FuncRequest(LFUN_PASTE, data));
271 void LCursor::resetAnchor()
278 bool LCursor::posLeft()
287 bool LCursor::posRight()
289 if (pos() == lastpos())
296 CursorSlice & LCursor::anchor()
298 BOOST_ASSERT(!anchor_.empty());
299 return anchor_.back();
303 CursorSlice const & LCursor::anchor() const
305 BOOST_ASSERT(!anchor_.empty());
306 return anchor_.back();
310 CursorSlice const & LCursor::selBegin() const
314 return anchor() < back() ? anchor() : back();
318 CursorSlice const & LCursor::selEnd() const
322 return anchor() > back() ? anchor() : back();
326 DocIterator LCursor::selectionBegin() const
330 return anchor() < back() ? anchor_ : *this;
334 DocIterator LCursor::selectionEnd() const
338 return anchor() > back() ? anchor_ : *this;
342 void LCursor::setSelection()
345 // a selection with no contents is not a selection
346 if (par() == anchor().par() && pos() == anchor().pos())
351 void LCursor::setSelection(DocIterator const & where, size_t n)
353 setCursor(where, true);
359 void LCursor::clearSelection()
368 int & LCursor::x_target()
374 int LCursor::x_target() const
380 void LCursor::clearTargetX()
387 void LCursor::info(std::ostream & os) const
389 for (int i = 1, n = depth(); i < n; ++i) {
390 operator[](i).inset().infoize(os);
394 prevInset()->infoize2(os);
395 // overwite old message
400 string LCursor::grabSelection()
405 CursorSlice i1 = selBegin();
406 CursorSlice i2 = selEnd();
408 if (i1.idx() == i2.idx()) {
409 if (i1.inset().asMathInset()) {
410 MathArray::const_iterator it = i1.cell().begin();
411 return asString(MathArray(it + i1.pos(), it + i2.pos()));
413 return "unknown selection 1";
419 region(i1, i2, r1, r2, c1, c2);
422 if (i1.inset().asMathInset()) {
423 for (row_type row = r1; row <= r2; ++row) {
426 for (col_type col = c1; col <= c2; ++col) {
429 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
433 data = "unknown selection 2";
439 void LCursor::eraseSelection()
441 //lyxerr << "LCursor::eraseSelection" << endl;
442 CursorSlice const & i1 = selBegin();
443 CursorSlice const & i2 = selEnd();
445 if (i1.inset().asMathInset()) {
446 if (i1.idx() == i2.idx()) {
447 i1.cell().erase(i1.pos(), i2.pos());
449 MathInset * p = i1.asMathInset();
452 region(i1, i2, r1, r2, c1, c2);
453 for (row_type row = r1; row <= r2; ++row)
454 for (col_type col = c1; col <= c2; ++col)
455 p->cell(p->index(row, col)).clear();
459 lyxerr << "can't erase this selection 1" << endl;
461 //lyxerr << "LCursor::eraseSelection end" << endl;
465 string LCursor::grabAndEraseSelection()
469 string res = grabSelection();
476 void LCursor::selClear()
483 void LCursor::selCopy()
486 theCutBuffer.push(grabSelection());
489 //theCutBuffer.erase();
494 void LCursor::selCut()
496 theCutBuffer.push(grabAndEraseSelection());
500 void LCursor::selDel()
502 //lyxerr << "LCursor::selDel" << endl;
510 void LCursor::selPaste(size_t n)
513 if (n < theCutBuffer.size())
514 paste(theCutBuffer[n]);
520 void LCursor::selHandle(bool sel)
522 //lyxerr << "LCursor::selHandle" << endl;
523 if (sel == selection())
530 void LCursor::selClearOrDel()
532 //lyxerr << "LCursor::selClearOrDel" << endl;
533 if (lyxrc.auto_region_delete)
540 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
542 for (size_t i = 0, n = cur.size(); i != n; ++i) {
543 os << " " << cur.operator[](i) << " | ";
544 if (i < cur.anchor_.size())
545 os << cur.anchor_[i];
547 os << "-------------------------------";
550 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
551 os << "------------------------------- | " << cur.anchor_[i] << "\n";
553 os << " selection: " << cur.selection_
554 << " x_target: " << cur.x_target_ << endl;
561 ///////////////////////////////////////////////////////////////////
563 // The part below is the non-integrated rest of the original math
564 // cursor. This should be either generalized for texted or moved
565 // back to mathed (in most cases to MathNestInset).
567 ///////////////////////////////////////////////////////////////////
569 #include "mathed/math_charinset.h"
570 #include "mathed/math_factory.h"
571 #include "mathed/math_gridinset.h"
572 #include "mathed/math_macroarg.h"
573 #include "mathed/math_macrotemplate.h"
574 #include "mathed/math_mathmlstream.h"
575 #include "mathed/math_scriptinset.h"
576 #include "mathed/math_support.h"
577 #include "mathed/math_unknowninset.h"
579 //#define FILEDEBUG 1
582 bool LCursor::isInside(InsetBase const * p)
584 for (unsigned i = 0; i < depth(); ++i)
585 if (&operator[](i).inset() == p)
591 bool LCursor::openable(MathAtom const & t) const
602 // we can't move into anything new during selection
603 if (depth() >= anchor_.size())
605 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
612 bool positionable(DocIterator const & cursor,
613 DocIterator const & anchor)
615 // avoid deeper nested insets when selecting
616 if (cursor.size() > anchor.size())
619 // anchor might be deeper, should have same path then
620 for (size_t i = 0; i < cursor.size(); ++i)
621 if (&cursor[i].inset() != &anchor[i].inset())
624 // position should be ok.
629 void LCursor::setScreenPos(int x, int y)
632 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
637 void LCursor::plainErase()
643 void LCursor::markInsert()
645 cell().insert(pos(), MathAtom(new MathCharInset(0)));
649 void LCursor::markErase()
655 void LCursor::plainInsert(MathAtom const & t)
657 cell().insert(pos(), t);
662 void LCursor::insert(string const & str)
664 lyxerr << "LCursor::insert str '" << str << "'" << endl;
665 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
670 void LCursor::insert(char c)
672 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
673 BOOST_ASSERT(!empty());
676 plainInsert(MathAtom(new MathCharInset(c)));
678 text()->insertChar(*this, c);
683 void LCursor::insert(MathAtom const & t)
685 //lyxerr << "LCursor::insert MathAtom: " << endl;
692 void LCursor::insert(InsetBase * inset)
695 insert(MathAtom(inset));
697 text()->insertInset(*this, inset);
701 void LCursor::niceInsert(string const & t)
712 void LCursor::niceInsert(MathAtom const & t)
715 string safe = grabAndEraseSelection();
717 // enter the new inset and move the contents of the selection if possible
720 // be careful here: don't use 'pushLeft(t)' as this we need to
721 // push the clone, not the original
722 pushLeft(*nextInset());
728 void LCursor::insert(MathArray const & ar)
733 cell().insert(pos(), ar);
738 bool LCursor::backspace()
740 autocorrect() = false;
748 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
755 MathUnknownInset * p = activeMacro();
756 if (p->name().size() > 1) {
757 p->setName(p->name().substr(0, p->name().size() - 1));
762 if (pos() != 0 && prevAtom()->nargs() > 0) {
763 // let's require two backspaces for 'big stuff' and
764 // highlight on the first
775 bool LCursor::erase()
777 autocorrect() = false;
786 // delete empty cells if possible
787 if (pos() == lastpos() && inset().idxDelete(idx()))
790 // special behaviour when in last position of cell
791 if (pos() == lastpos()) {
792 bool one_cell = inset().nargs() == 1;
793 if (one_cell && depth() == 1 && lastpos() == 0)
799 inset().idxGlue(idx());
803 if (pos() != lastpos() && inset().nargs() > 0) {
817 DocIterator save = *this;
820 setCursor(save, false);
821 autocorrect() = false;
829 DocIterator save = *this;
832 setCursor(save, false);
833 autocorrect() = false;
838 void LCursor::macroModeClose()
842 MathUnknownInset * p = activeMacro();
844 string s = p->name();
848 // do nothing if the macro name is empty
852 string const name = s.substr(1);
854 // prevent entering of recursive macros
855 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
856 if (macro && macro->getInsetName() == name)
857 lyxerr << "can't enter recursive macro" << endl;
859 niceInsert(createMathInset(name));
863 string LCursor::macroName()
865 return inMacroMode() ? activeMacro()->name() : string();
869 void LCursor::handleNest(MathAtom const & a, int c)
871 //lyxerr << "LCursor::handleNest: " << c << endl;
873 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
876 pushLeft(*nextInset());
880 int LCursor::targetX() const
882 if (x_target() != -1)
891 void LCursor::adjust(pos_type from, int diff)
895 if (anchor().pos() > from)
896 anchor().pos() += diff;
897 // just to be on the safe side
898 // theoretically unecessary
903 bool LCursor::inMacroMode() const
907 MathUnknownInset const * p = prevAtom()->asUnknownInset();
908 return p && !p->final();
912 MathUnknownInset * LCursor::activeMacro()
914 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
918 bool LCursor::inMacroArgMode() const
920 return pos() > 0 && prevAtom()->getChar() == '#';
924 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
926 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
927 MathInset * m = operator[](i).inset().asMathInset();
930 MathGridInset * p = m->asGridInset();
932 idx = operator[](i).idx();
940 void LCursor::pullArg()
943 MathArray ar = cell();
944 if (popLeft() && inMathed()) {
946 cell().insert(pos(), ar);
949 //formula()->mutateToText();
954 void LCursor::touch()
958 DocIterator::const_iterator it = begin();
959 DocIterator::const_iterator et = end();
960 for ( ; it != et; ++it)
966 void LCursor::normalize()
968 if (idx() >= nargs()) {
969 lyxerr << "this should not really happen - 1: "
970 << idx() << ' ' << nargs()
971 << " in: " << &inset() << endl;
973 idx() = min(idx(), lastidx());
975 if (pos() > lastpos()) {
976 lyxerr << "this should not really happen - 2: "
977 << pos() << ' ' << lastpos() << " in idx: " << idx()
979 WriteStream wi(lyxerr, false, true);
980 inset().asMathInset()->write(wi);
983 pos() = min(pos(), lastpos());
987 char LCursor::valign()
990 MathGridInset * p = enclosingGrid(idx);
991 return p ? p->valign() : '\0';
995 char LCursor::halign()
998 MathGridInset * p = enclosingGrid(idx);
999 return p ? p->halign(idx % p->ncols()) : '\0';
1003 bool LCursor::goUpDown(bool up)
1005 // Be warned: The 'logic' implemented in this function is highly
1006 // fragile. A distance of one pixel or a '<' vs '<=' _really
1007 // matters. So fiddle around with it only if you think you know
1008 // what you are doing!
1014 // check if we had something else in mind, if not, this is the future goal
1015 if (x_target() == -1)
1020 // try neigbouring script insets
1024 MathScriptInset const * p = prevAtom()->asScriptInset();
1025 if (p && p->has(up)) {
1028 idx() = up; // the superscript has index 1
1030 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1036 if (pos() != lastpos()) {
1037 MathScriptInset const * p = nextAtom()->asScriptInset();
1038 if (p && p->has(up)) {
1042 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1048 // try current cell for e.g. text insets
1049 if (inset().idxUpDown2(*this, up))
1052 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1057 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1058 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1062 // try to find an inset that knows better then we
1064 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1066 if (inset().idxUpDown(*this, up)) {
1067 // try to find best position within this inset
1073 // no such inset found, just take something "above"
1074 //lyxerr << "updown: handled by strange case" << endl;
1076 int ylow = up ? 0 : yo + 1;
1077 int yhigh = up ? yo - 1 : bv().workHeight();
1078 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1081 // any improvement so far?
1084 if (up ? ynew < yo : ynew > yo)
1090 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1092 BOOST_ASSERT(!empty());
1094 CursorSlice bottom = operator[](0);
1095 LyXText * text = bottom.text();
1097 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1099 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1100 DocIterator et = doc_iterator_end(bv().buffer()->inset());
1101 //lyxerr << "x: " << x << " y: " << y << endl;
1102 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1103 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1106 //et.par() = text->parOffset(end);
1108 double best_dist = 10e10;
1109 DocIterator best_cursor = it;
1111 for ( ; it != et; it.forwardPos()) {
1112 // avoid invalid nesting when selecting
1113 if (!selection() || positionable(it, anchor_)) {
1115 CursorSlice & cur = it.back();
1116 cur.inset().getCursorPos(cur, xo, yo);
1117 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1118 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1119 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1120 // '<=' in order to take the last possible position
1121 // this is important for clicking behind \sum in e.g. '\sum_i a'
1122 if (d <= best_dist) {
1123 //lyxerr << "*" << endl;
1131 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1132 if (best_dist < 1e10)
1133 setCursor(best_cursor, false);
1134 return best_dist < 1e10;
1138 void LCursor::bruteFind2(int x, int y)
1140 double best_dist = 1e10;
1142 DocIterator it = *this;
1143 it.back().pos() = 0;
1144 DocIterator et = *this;
1145 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1146 for (int i = 0; ; ++i) {
1148 CursorSlice & cur = it.back();
1149 cur.inset().getCursorPos(cur, xo, yo);
1150 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1151 // '<=' in order to take the last possible position
1152 // this is important for clicking behind \sum in e.g. '\sum_i a'
1153 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1154 if (d <= best_dist) {
1156 setCursor(it, false);
1165 CursorSlice LCursor::normalAnchor()
1167 if (anchor_.size() < depth()) {
1169 lyxerr << "unusual Anchor size" << endl;
1171 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1172 // use Anchor on the same level as Cursor
1173 CursorSlice normal = anchor_[size() - 1];
1175 if (depth() < anchor_.size() && !(normal < xx())) {
1176 // anchor is behind cursor -> move anchor behind the inset
1184 void LCursor::handleFont(string const & font)
1186 lyxerr << "LCursor::handleFont: " << font << endl;
1190 safe = grabAndEraseSelection();
1193 if (lastpos() != 0) {
1194 // something left in the cell
1196 // cursor in first position
1198 } else if (pos() == lastpos()) {
1199 // cursor in last position
1202 // cursor in between. split cell
1203 MathArray::iterator bt = cell().begin();
1204 MathAtom at = createMathInset(font);
1205 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1206 cell().erase(bt, bt + pos());
1211 // nothing left in the cell
1219 void LCursor::message(string const & msg) const
1221 bv().owner()->getLyXFunc().setMessage(msg);
1225 void LCursor::errorMessage(string const & msg) const
1227 bv().owner()->getLyXFunc().setErrorMessage(msg);
1231 string LCursor::selectionAsString(bool label) const
1237 Buffer const & buffer = *bv().buffer();
1238 ParagraphList & pars = text()->paragraphs();
1240 // should be const ...
1241 par_type startpit = selBegin().par();
1242 par_type endpit = selEnd().par();
1243 size_t const startpos = selBegin().pos();
1244 size_t const endpos = selEnd().pos();
1246 if (startpit == endpit)
1247 return pars[startpit].asString(buffer, startpos, endpos, label);
1249 // First paragraph in selection
1250 string result = pars[startpit].
1251 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1253 // The paragraphs in between (if any)
1254 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1255 Paragraph & par = pars[pit];
1256 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1259 // Last paragraph in selection
1260 result += pars[endpit].asString(buffer, 0, endpos, label);
1265 #warning and mathed?
1270 string LCursor::currentState()
1273 std::ostringstream os;
1279 return text()->currentState(*this);
1285 string LCursor::getPossibleLabel()
1287 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1291 Encoding const * LCursor::getEncoding() const
1298 // go up until first non-0 text is hit
1299 // (innermost text is 0 in mathed)
1300 for (s = size() - 1; s >= 0; --s)
1301 if (operator[](s).text())
1303 CursorSlice const & sl = operator[](s);
1304 LyXText & text = *sl.text();
1305 LyXFont font = text.getPar(sl.par()).getFont(
1306 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1307 return font.language()->encoding();
1311 void LCursor::undispatched()
1313 disp_.dispatched(false);
1317 void LCursor::dispatched()
1319 disp_.dispatched(true);
1323 void LCursor::noUpdate()
1325 disp_.update(false);