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;
140 disp_.dispatched(false);
146 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
148 // This is, of course, a mess. Better create a new doc iterator and use
149 // this in Inset::getStatus. This might require an additional
150 // BufferView * arg, though (which should be avoided)
151 LCursor safe = *this;
153 for ( ; size(); pop()) {
154 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
155 BOOST_ASSERT(pos() <= lastpos());
156 BOOST_ASSERT(idx() <= lastidx());
157 BOOST_ASSERT(par() <= lastpar());
159 // The inset's getStatus() will return 'true' if it made
160 // a definitive decision on whether it want to handle the
161 // request or not. The result of this decision is put into
162 // the 'status' parameter.
163 if (inset().getStatus(*this, cmd, status)) {
173 BufferView & LCursor::bv() const
180 Buffer & LCursor::buffer() const
183 BOOST_ASSERT(bv_->buffer());
184 return *bv_->buffer();
190 BOOST_ASSERT(size() >= 1);
195 void LCursor::push(InsetBase & p)
197 push_back(CursorSlice(p));
201 void LCursor::pushLeft(InsetBase & p)
203 BOOST_ASSERT(!empty());
204 //lyxerr << "Entering inset " << t << " left" << endl;
210 bool LCursor::popLeft()
212 BOOST_ASSERT(!empty());
213 //lyxerr << "Leaving inset to the left" << endl;
214 inset().notifyCursorLeaves(*this);
222 bool LCursor::popRight()
224 BOOST_ASSERT(!empty());
225 //lyxerr << "Leaving inset to the right" << endl;
226 inset().notifyCursorLeaves(*this);
235 int LCursor::currentMode()
237 BOOST_ASSERT(!empty());
238 for (int i = size() - 1; i >= 0; --i) {
239 int res = operator[](i).inset().currentMode();
240 if (res != InsetBase::UNDECIDED_MODE)
243 return InsetBase::TEXT_MODE;
247 void LCursor::getDim(int & asc, int & des) const
250 BOOST_ASSERT(inset().asMathInset());
251 //inset().asMathInset()->getCursorDim(asc, des);
254 } else if (inTexted()) {
255 Row const & row = textRow();
256 asc = row.baseline();
257 des = row.height() - asc;
259 lyxerr << "should this happen?" << endl;
266 void LCursor::getPos(int & x, int & y) const
271 inset().getCursorPos(back(), x, y);
275 void LCursor::paste(string const & data)
277 dispatch(FuncRequest(LFUN_PASTE, data));
281 void LCursor::resetAnchor()
288 bool LCursor::posLeft()
297 bool LCursor::posRight()
299 if (pos() == lastpos())
306 CursorSlice LCursor::anchor() const
308 BOOST_ASSERT(anchor_.size() >= size());
309 CursorSlice normal = anchor_[size() - 1];
310 if (size() < anchor_.size() && back() <= normal) {
311 // anchor is behind cursor -> move anchor behind the inset
318 CursorSlice LCursor::selBegin() const
322 return anchor() < back() ? anchor() : back();
326 CursorSlice LCursor::selEnd() const
330 return anchor() > back() ? anchor() : back();
334 DocIterator LCursor::selectionBegin() const
338 return anchor() < back() ? anchor_ : *this;
342 DocIterator LCursor::selectionEnd() const
346 return anchor() > back() ? anchor_ : *this;
350 void LCursor::setSelection()
353 // a selection with no contents is not a selection
354 #warning doesnt look ok
355 if (par() == anchor().par() && pos() == anchor().pos())
360 void LCursor::setSelection(DocIterator const & where, size_t n)
362 setCursor(where, true);
368 void LCursor::clearSelection()
377 int & LCursor::x_target()
383 int LCursor::x_target() const
389 void LCursor::clearTargetX()
396 void LCursor::info(std::ostream & os) const
398 for (int i = 1, n = depth(); i < n; ++i) {
399 operator[](i).inset().infoize(os);
403 prevInset()->infoize2(os);
404 // overwite old message
409 string LCursor::grabSelection()
414 CursorSlice i1 = selBegin();
415 CursorSlice i2 = selEnd();
417 if (i1.idx() == i2.idx()) {
418 if (i1.inset().asMathInset()) {
419 MathArray::const_iterator it = i1.cell().begin();
420 return asString(MathArray(it + i1.pos(), it + i2.pos()));
422 return "unknown selection 1";
428 region(i1, i2, r1, r2, c1, c2);
431 if (i1.inset().asMathInset()) {
432 for (row_type row = r1; row <= r2; ++row) {
435 for (col_type col = c1; col <= c2; ++col) {
438 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
442 data = "unknown selection 2";
448 void LCursor::eraseSelection()
450 //lyxerr << "LCursor::eraseSelection" << endl;
451 CursorSlice const & i1 = selBegin();
452 CursorSlice const & i2 = selEnd();
456 if (i1.inset().asMathInset()) {
457 if (i1.idx() == i2.idx()) {
458 i1.cell().erase(i1.pos(), i2.pos());
460 MathInset * p = i1.asMathInset();
463 region(i1, i2, r1, r2, c1, c2);
464 for (row_type row = r1; row <= r2; ++row)
465 for (col_type col = c1; col <= c2; ++col)
466 p->cell(p->index(row, col)).clear();
470 lyxerr << "can't erase this selection 1" << endl;
472 //lyxerr << "LCursor::eraseSelection end" << endl;
476 string LCursor::grabAndEraseSelection()
480 string res = grabSelection();
487 void LCursor::selCopy()
490 theCutBuffer.push(grabSelection());
493 //theCutBuffer.erase();
498 void LCursor::selCut()
500 theCutBuffer.push(grabAndEraseSelection());
504 void LCursor::selDel()
506 //lyxerr << "LCursor::selDel" << endl;
514 void LCursor::selPaste(size_t n)
517 if (n < theCutBuffer.size())
518 paste(theCutBuffer[n]);
524 void LCursor::selHandle(bool sel)
526 //lyxerr << "LCursor::selHandle" << endl;
527 if (sel == selection()) {
538 void LCursor::selClearOrDel()
540 //lyxerr << "LCursor::selClearOrDel" << endl;
541 if (lyxrc.auto_region_delete)
548 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
550 for (size_t i = 0, n = cur.size(); i != n; ++i) {
551 os << " " << cur.operator[](i) << " | ";
552 if (i < cur.anchor_.size())
553 os << cur.anchor_[i];
555 os << "-------------------------------";
558 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
559 os << "------------------------------- | " << cur.anchor_[i] << "\n";
561 os << " selection: " << cur.selection_
562 << " x_target: " << cur.x_target_ << endl;
569 ///////////////////////////////////////////////////////////////////
571 // The part below is the non-integrated rest of the original math
572 // cursor. This should be either generalized for texted or moved
573 // back to mathed (in most cases to MathNestInset).
575 ///////////////////////////////////////////////////////////////////
577 #include "mathed/math_charinset.h"
578 #include "mathed/math_factory.h"
579 #include "mathed/math_gridinset.h"
580 #include "mathed/math_macroarg.h"
581 #include "mathed/math_mathmlstream.h"
582 #include "mathed/math_scriptinset.h"
583 #include "mathed/math_support.h"
584 #include "mathed/math_unknowninset.h"
586 //#define FILEDEBUG 1
589 bool LCursor::isInside(InsetBase const * p)
591 for (unsigned i = 0; i < depth(); ++i)
592 if (&operator[](i).inset() == p)
598 bool LCursor::openable(MathAtom const & t) const
609 // we can't move into anything new during selection
610 if (depth() >= anchor_.size())
612 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
619 bool positionable(DocIterator const & cursor,
620 DocIterator const & anchor)
622 // avoid deeper nested insets when selecting
623 if (cursor.size() > anchor.size())
626 // anchor might be deeper, should have same path then
627 for (size_t i = 0; i < cursor.size(); ++i)
628 if (&cursor[i].inset() != &anchor[i].inset())
631 // position should be ok.
636 void LCursor::setScreenPos(int x, int y)
639 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
644 void LCursor::plainErase()
650 void LCursor::markInsert()
656 void LCursor::markErase()
662 void LCursor::plainInsert(MathAtom const & t)
664 cell().insert(pos(), t);
669 void LCursor::insert(string const & str)
671 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
672 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
677 void LCursor::insert(char c)
679 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
680 BOOST_ASSERT(!empty());
683 insert(new MathCharInset(c));
685 text()->insertChar(*this, c);
690 void LCursor::insert(MathAtom const & t)
692 //lyxerr << "LCursor::insert MathAtom: " << endl;
696 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
700 void LCursor::insert(InsetBase * inset)
703 insert(MathAtom(inset));
705 text()->insertInset(*this, inset);
709 void LCursor::niceInsert(string const & t)
720 void LCursor::niceInsert(MathAtom const & t)
723 string safe = grabAndEraseSelection();
725 // enter the new inset and move the contents of the selection if possible
728 // be careful here: don't use 'pushLeft(t)' as this we need to
729 // push the clone, not the original
730 pushLeft(*nextInset());
736 void LCursor::insert(MathArray const & ar)
741 cell().insert(pos(), ar);
746 bool LCursor::backspace()
748 autocorrect() = false;
756 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
763 MathUnknownInset * p = activeMacro();
764 if (p->name().size() > 1) {
765 p->setName(p->name().substr(0, p->name().size() - 1));
770 if (pos() != 0 && prevAtom()->nargs() > 0) {
771 // let's require two backspaces for 'big stuff' and
772 // highlight on the first
784 bool LCursor::erase()
786 autocorrect() = false;
795 // delete empty cells if possible
796 if (pos() == lastpos() && inset().idxDelete(idx()))
799 // special behaviour when in last position of cell
800 if (pos() == lastpos()) {
801 bool one_cell = inset().nargs() == 1;
802 if (one_cell && depth() == 1 && lastpos() == 0)
808 inset().idxGlue(idx());
812 // 'clever' UI hack: only erase large items if previously slected
813 if (pos() != lastpos() && inset().nargs() > 0) {
828 DocIterator save = *this;
831 setCursor(save, false);
832 autocorrect() = false;
840 DocIterator save = *this;
843 setCursor(save, false);
844 autocorrect() = false;
849 void LCursor::macroModeClose()
853 MathUnknownInset * p = activeMacro();
855 string s = p->name();
859 // do nothing if the macro name is empty
863 string const name = s.substr(1);
865 // prevent entering of recursive macros
866 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
867 if (macro && macro->getInsetName() == name)
868 lyxerr << "can't enter recursive macro" << endl;
870 niceInsert(createMathInset(name));
874 string LCursor::macroName()
876 return inMacroMode() ? activeMacro()->name() : string();
880 void LCursor::handleNest(MathAtom const & a, int c)
882 //lyxerr << "LCursor::handleNest: " << c << endl;
884 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
887 pushLeft(*nextInset());
891 int LCursor::targetX() const
893 if (x_target() != -1)
902 bool LCursor::inMacroMode() const
906 MathUnknownInset const * p = prevAtom()->asUnknownInset();
907 return p && !p->final();
911 MathUnknownInset * LCursor::activeMacro()
913 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
917 void LCursor::pullArg()
922 MathArray ar = cell();
923 if (popLeft() && inMathed()) {
925 cell().insert(pos(), ar);
928 //formula()->mutateToText();
933 void LCursor::touch()
939 DocIterator::const_iterator it = begin();
940 DocIterator::const_iterator et = end();
941 for ( ; it != et; ++it)
947 void LCursor::normalize()
949 if (idx() >= nargs()) {
950 lyxerr << "this should not really happen - 1: "
951 << idx() << ' ' << nargs()
952 << " in: " << &inset() << endl;
954 idx() = min(idx(), lastidx());
956 if (pos() > lastpos()) {
957 lyxerr << "this should not really happen - 2: "
958 << pos() << ' ' << lastpos() << " in idx: " << idx()
960 WriteStream wi(lyxerr, false, true);
961 inset().asMathInset()->write(wi);
964 pos() = min(pos(), lastpos());
968 bool LCursor::goUpDown(bool up)
970 // Be warned: The 'logic' implemented in this function is highly
971 // fragile. A distance of one pixel or a '<' vs '<=' _really
972 // matters. So fiddle around with it only if you think you know
973 // what you are doing!
979 // check if we had something else in mind, if not, this is the future goal
980 if (x_target() == -1)
985 // try neigbouring script insets
989 MathScriptInset const * p = prevAtom()->asScriptInset();
990 if (p && p->has(up)) {
993 idx() = up; // the superscript has index 1
995 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1001 if (pos() != lastpos()) {
1002 MathScriptInset const * p = nextAtom()->asScriptInset();
1003 if (p && p->has(up)) {
1007 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1013 // try current cell for e.g. text insets
1014 if (inset().idxUpDown2(*this, up))
1017 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1022 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1023 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1027 // try to find an inset that knows better then we
1029 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1031 if (inset().idxUpDown(*this, up)) {
1032 // try to find best position within this inset
1038 // no such inset found, just take something "above"
1039 //lyxerr << "updown: handled by strange case" << endl;
1041 int ylow = up ? 0 : yo + 1;
1042 int yhigh = up ? yo - 1 : bv().workHeight();
1043 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1046 // any improvement so far?
1049 if (up ? ynew < yo : ynew > yo)
1055 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1057 BOOST_ASSERT(!empty());
1059 CursorSlice bottom = operator[](0);
1060 LyXText * text = bottom.text();
1062 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1064 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1065 DocIterator et = doc_iterator_end(bv().buffer()->inset());
1066 //lyxerr << "x: " << x << " y: " << y << endl;
1067 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1068 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1071 //et.par() = text->parOffset(end);
1073 double best_dist = 10e10;
1074 DocIterator best_cursor = it;
1076 for ( ; it != et; it.forwardPos()) {
1077 // avoid invalid nesting when selecting
1078 if (!selection() || positionable(it, anchor_)) {
1080 CursorSlice & cur = it.back();
1081 cur.inset().getCursorPos(cur, xo, yo);
1082 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1083 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1084 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1085 // '<=' in order to take the last possible position
1086 // this is important for clicking behind \sum in e.g. '\sum_i a'
1087 if (d <= best_dist) {
1088 //lyxerr << "*" << endl;
1096 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1097 if (best_dist < 1e10)
1098 setCursor(best_cursor, false);
1099 return best_dist < 1e10;
1103 void LCursor::bruteFind2(int x, int y)
1105 double best_dist = 1e10;
1107 DocIterator it = *this;
1108 it.back().pos() = 0;
1109 DocIterator et = *this;
1110 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1111 for (int i = 0; ; ++i) {
1113 CursorSlice & cur = it.back();
1114 cur.inset().getCursorPos(cur, xo, yo);
1115 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1116 // '<=' in order to take the last possible position
1117 // this is important for clicking behind \sum in e.g. '\sum_i a'
1118 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1119 if (d <= best_dist) {
1121 setCursor(it, false);
1130 void LCursor::handleFont(string const & font)
1132 lyxerr << "LCursor::handleFont: " << font << endl;
1136 safe = grabAndEraseSelection();
1139 if (lastpos() != 0) {
1140 // something left in the cell
1142 // cursor in first position
1144 } else if (pos() == lastpos()) {
1145 // cursor in last position
1148 // cursor in between. split cell
1149 MathArray::iterator bt = cell().begin();
1150 MathAtom at = createMathInset(font);
1151 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1152 cell().erase(bt, bt + pos());
1157 // nothing left in the cell
1165 void LCursor::message(string const & msg) const
1167 bv().owner()->getLyXFunc().setMessage(msg);
1171 void LCursor::errorMessage(string const & msg) const
1173 bv().owner()->getLyXFunc().setErrorMessage(msg);
1177 string LCursor::selectionAsString(bool label) const
1183 Buffer const & buffer = *bv().buffer();
1184 ParagraphList & pars = text()->paragraphs();
1186 // should be const ...
1187 par_type startpit = selBegin().par();
1188 par_type endpit = selEnd().par();
1189 size_t const startpos = selBegin().pos();
1190 size_t const endpos = selEnd().pos();
1192 if (startpit == endpit)
1193 return pars[startpit].asString(buffer, startpos, endpos, label);
1195 // First paragraph in selection
1196 string result = pars[startpit].
1197 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1199 // The paragraphs in between (if any)
1200 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1201 Paragraph & par = pars[pit];
1202 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1205 // Last paragraph in selection
1206 result += pars[endpit].asString(buffer, 0, endpos, label);
1211 #ifdef WITH_WARNINGS
1212 #warning and mathed?
1218 string LCursor::currentState()
1221 std::ostringstream os;
1227 return text()->currentState(*this);
1233 string LCursor::getPossibleLabel()
1235 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1239 Encoding const * LCursor::getEncoding() const
1246 // go up until first non-0 text is hit
1247 // (innermost text is 0 in mathed)
1248 for (s = size() - 1; s >= 0; --s)
1249 if (operator[](s).text())
1251 CursorSlice const & sl = operator[](s);
1252 LyXText & text = *sl.text();
1253 LyXFont font = text.getPar(sl.par()).getFont(
1254 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1255 return font.language()->encoding();
1259 void LCursor::undispatched()
1261 disp_.dispatched(false);
1265 void LCursor::dispatched()
1267 disp_.dispatched(true);
1271 void LCursor::noUpdate()
1273 disp_.update(false);