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 "coordcache.h"
19 #include "CutAndPaste.h"
21 #include "dispatchresult.h"
23 #include "funcrequest.h"
27 #include "lyxfunc.h" // only for setMessage()
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.h"
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
38 #include "mathed/math_data.h"
39 #include "mathed/math_inset.h"
40 #include "mathed/math_scriptinset.h"
41 #include "mathed/math_macrotable.h"
43 #include "support/limited_stack.h"
45 #include "frontends/LyXView.h"
46 #include "frontends/font_metrics.h"
48 #include <boost/assert.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/current_function.hpp>
60 #ifndef CXX_GLOBAL_CSTD
69 positionable(DocIterator const & cursor, DocIterator const & anchor)
71 // avoid deeper nested insets when selecting
72 if (cursor.depth() > anchor.depth())
75 // anchor might be deeper, should have same path then
76 for (size_t i = 0; i < cursor.depth(); ++i)
77 if (&cursor[i].inset() != &anchor[i].inset())
80 // position should be ok.
85 // Find position closest to (x, y) in cell given by iter.
86 // Used only in mathed
87 DocIterator bruteFind2(LCursor const & c, int x, int y)
89 double best_dist = std::numeric_limits<double>::max();
96 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
97 for (size_t i = 0; ; ++i) {
100 InsetBase const * inset = &it.inset();
101 Point o = theCoords.getInsets().xy(inset);
102 inset->cursorPos(it.top(), c.boundary(), xo, yo);
103 // Convert to absolute
106 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
107 // '<=' in order to take the last possible position
108 // this is important for clicking behind \sum in e.g. '\sum_i a'
109 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
110 << " best: " << best_dist << endl;
111 if (d <= best_dist) {
123 /// moves position closest to (x, y) in given box
124 bool bruteFind(LCursor & cursor,
125 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
127 BOOST_ASSERT(!cursor.empty());
128 InsetBase & inset = cursor[0].inset();
130 DocIterator it = doc_iterator_begin(inset);
131 DocIterator const et = doc_iterator_end(inset);
133 double best_dist = std::numeric_limits<double>::max();;
134 DocIterator best_cursor = et;
136 for ( ; it != et; it.forwardPos(true)) {
137 // avoid invalid nesting when selecting
138 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
139 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
140 Point p = bv_funcs::getPos(it, false);
143 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
144 double const dx = xo - x;
145 double const dy = yo - y;
146 double const d = dx * dx + dy * dy;
147 // '<=' in order to take the last possible position
148 // this is important for clicking behind \sum in e.g. '\sum_i a'
149 if (d <= best_dist) {
150 lyxerr << "*" << endl;
158 if (best_cursor != et) {
159 cursor.setCursor(best_cursor);
167 /// moves position closest to (x, y) in given box
168 bool bruteFind3(LCursor & cur, int x, int y, bool up)
170 BufferView & bv = cur.bv();
171 int ylow = up ? 0 : y + 1;
172 int yhigh = up ? y - 1 : bv.workHeight();
174 int xhigh = bv.workWidth();
176 // FIXME: bit more work needed to get 'from' and 'to' right.
177 pit_type from = cur.bottom().pit();
178 //pit_type to = cur.bottom().pit();
179 //lyxerr << "Pit start: " << from << endl;
181 //lyxerr << "bruteFind3: x: " << x << " y: " << y
182 // << " xlow: " << xlow << " xhigh: " << xhigh
183 // << " ylow: " << ylow << " yhigh: " << yhigh
185 InsetBase & inset = bv.buffer()->inset();
186 DocIterator it = doc_iterator_begin(inset);
188 DocIterator et = doc_iterator_end(inset);
190 double best_dist = std::numeric_limits<double>::max();
191 DocIterator best_cursor = et;
193 for ( ; it != et; it.forwardPos()) {
194 // avoid invalid nesting when selecting
195 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
196 && (!cur.selection() || positionable(it, cur.anchor_))) {
197 Point p = bv_funcs::getPos(it, false);
200 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
201 double const dx = xo - x;
202 double const dy = yo - y;
203 double const d = dx * dx + dy * dy;
204 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
205 // << " dx: " << dx << " dy: " << dy
206 // << " idx: " << it.idx() << " pos: " << it.pos()
209 // '<=' in order to take the last possible position
210 // this is important for clicking behind \sum in e.g. '\sum_i a'
211 if (d <= best_dist) {
212 //lyxerr << "*" << endl;
220 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
221 if (best_cursor == et)
223 cur.setCursor(best_cursor);
230 // be careful: this is called from the bv's constructor, too, so
231 // bv functions are not yet available!
232 LCursor::LCursor(BufferView & bv)
233 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
234 selection_(false), mark_(false), logicalpos_(false)
238 void LCursor::reset(InsetBase & inset)
241 push_back(CursorSlice(inset));
242 anchor_ = DocIterator(inset);
249 // this (intentionally) does neither touch anchor nor selection status
250 void LCursor::setCursor(DocIterator const & cur)
252 DocIterator::operator=(cur);
256 void LCursor::dispatch(FuncRequest const & cmd0)
258 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
259 << " cmd: " << cmd0 << '\n'
265 FuncRequest cmd = cmd0;
266 LCursor safe = *this;
268 for (; depth(); pop()) {
269 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
270 << cmd0 << endl << *this << endl;
271 BOOST_ASSERT(pos() <= lastpos());
272 BOOST_ASSERT(idx() <= lastidx());
273 BOOST_ASSERT(pit() <= lastpit());
275 // The common case is 'LFUN handled, need update', so make the
276 // LFUN handler's life easier by assuming this as default value.
277 // The handler can reset the update and val flags if necessary.
279 disp_.dispatched(true);
280 inset().dispatch(*this, cmd);
281 if (disp_.dispatched())
284 // it completely to get a 'bomb early' behaviour in case this
285 // object will be used again.
286 if (!disp_.dispatched()) {
287 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
289 disp_.dispatched(false);
294 DispatchResult LCursor::result() const
300 BufferView & LCursor::bv() const
307 Buffer & LCursor::buffer() const
310 BOOST_ASSERT(bv_->buffer());
311 return *bv_->buffer();
317 BOOST_ASSERT(depth() >= 1);
322 void LCursor::push(InsetBase & p)
324 push_back(CursorSlice(p));
328 void LCursor::pushLeft(InsetBase & p)
330 BOOST_ASSERT(!empty());
331 //lyxerr << "Entering inset " << t << " left" << endl;
337 bool LCursor::popLeft()
339 BOOST_ASSERT(!empty());
340 //lyxerr << "Leaving inset to the left" << endl;
341 inset().notifyCursorLeaves(*this);
349 bool LCursor::popRight()
351 BOOST_ASSERT(!empty());
352 //lyxerr << "Leaving inset to the right" << endl;
353 inset().notifyCursorLeaves(*this);
362 int LCursor::currentMode()
364 BOOST_ASSERT(!empty());
365 for (int i = depth() - 1; i >= 0; --i) {
366 int res = operator[](i).inset().currentMode();
367 if (res != InsetBase::UNDECIDED_MODE)
370 return InsetBase::TEXT_MODE;
374 void LCursor::getPos(int & x, int & y) const
376 Point p = bv_funcs::getPos(*this, boundary());
382 void LCursor::resetAnchor()
389 bool LCursor::posLeft()
398 bool LCursor::posRight()
400 if (pos() == lastpos())
407 CursorSlice LCursor::anchor() const
409 BOOST_ASSERT(anchor_.depth() >= depth());
410 CursorSlice normal = anchor_[depth() - 1];
411 if (depth() < anchor_.depth() && top() <= normal) {
412 // anchor is behind cursor -> move anchor behind the inset
419 CursorSlice LCursor::selBegin() const
423 return anchor() < top() ? anchor() : top();
427 CursorSlice LCursor::selEnd() const
431 return anchor() > top() ? anchor() : top();
435 DocIterator LCursor::selectionBegin() const
439 DocIterator di = (anchor() < top() ? anchor_ : *this);
445 DocIterator LCursor::selectionEnd() const
449 DocIterator di = (anchor() > top() ? anchor_ : *this);
450 if (di.depth() > depth()) {
458 void LCursor::setSelection()
461 // A selection with no contents is not a selection
463 #warning doesnt look ok
465 if (pit() == anchor().pit() && pos() == anchor().pos())
470 void LCursor::setSelection(DocIterator const & where, size_t n)
479 void LCursor::clearSelection()
488 int & LCursor::x_target()
494 int LCursor::x_target() const
500 void LCursor::clearTargetX()
507 void LCursor::info(std::ostream & os) const
509 for (int i = 1, n = depth(); i < n; ++i) {
510 operator[](i).inset().infoize(os);
514 prevInset()->infoize2(os);
515 // overwite old message
520 void LCursor::selHandle(bool sel)
522 //lyxerr << "LCursor::selHandle" << endl;
523 if (sel == selection())
531 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
533 os << "\n cursor: | anchor:\n";
534 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
535 os << " " << cur[i] << " | ";
536 if (i < cur.anchor_.depth())
537 os << cur.anchor_[i];
539 os << "-------------------------------";
542 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
543 os << "------------------------------- | " << cur.anchor_[i] << "\n";
545 os << " selection: " << cur.selection_
546 << " x_target: " << cur.x_target_ << endl;
553 ///////////////////////////////////////////////////////////////////
555 // The part below is the non-integrated rest of the original math
556 // cursor. This should be either generalized for texted or moved
557 // back to mathed (in most cases to MathNestInset).
559 ///////////////////////////////////////////////////////////////////
561 #include "mathed/math_charinset.h"
562 #include "mathed/math_factory.h"
563 #include "mathed/math_gridinset.h"
564 #include "mathed/math_macroarg.h"
565 #include "mathed/math_mathmlstream.h"
566 #include "mathed/math_scriptinset.h"
567 #include "mathed/math_support.h"
568 #include "mathed/math_unknowninset.h"
570 //#define FILEDEBUG 1
573 bool LCursor::isInside(InsetBase const * p)
575 for (size_t i = 0; i != depth(); ++i)
576 if (&operator[](i).inset() == p)
582 void LCursor::leaveInset(InsetBase const & inset)
584 for (size_t i = 0; i != depth(); ++i) {
585 if (&operator[](i).inset() == &inset) {
593 bool LCursor::openable(MathAtom const & t) const
604 // we can't move into anything new during selection
605 if (depth() >= anchor_.depth())
607 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
614 void LCursor::setScreenPos(int x, int y)
617 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
622 void LCursor::plainErase()
628 void LCursor::markInsert()
634 void LCursor::markErase()
640 void LCursor::plainInsert(MathAtom const & t)
642 cell().insert(pos(), t);
647 void LCursor::insert(string const & str)
649 for_each(str.begin(), str.end(),
650 boost::bind(static_cast<void(LCursor::*)(char)>
651 (&LCursor::insert), this, _1));
655 void LCursor::insert(char c)
657 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
658 BOOST_ASSERT(!empty());
660 lyx::cap::selClearOrDel(*this);
661 insert(new MathCharInset(c));
663 text()->insertChar(*this, c);
668 void LCursor::insert(MathAtom const & t)
670 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
672 lyx::cap::selClearOrDel(*this);
677 void LCursor::insert(InsetBase * inset)
680 insert(MathAtom(inset));
682 text()->insertInset(*this, inset);
686 void LCursor::niceInsert(string const & t)
697 void LCursor::niceInsert(MathAtom const & t)
700 string const safe = lyx::cap::grabAndEraseSelection(*this);
702 // enter the new inset and move the contents of the selection if possible
705 // be careful here: don't use 'pushLeft(t)' as this we need to
706 // push the clone, not the original
707 pushLeft(*nextInset());
708 // We may not use niceInsert here (recursion)
716 void LCursor::insert(MathArray const & ar)
720 lyx::cap::eraseSelection(*this);
721 cell().insert(pos(), ar);
726 bool LCursor::backspace()
728 autocorrect() = false;
731 lyx::cap::selDel(*this);
736 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
743 MathUnknownInset * p = activeMacro();
744 if (p->name().size() > 1) {
745 p->setName(p->name().substr(0, p->name().size() - 1));
750 if (pos() != 0 && prevAtom()->nargs() > 0) {
751 // let's require two backspaces for 'big stuff' and
752 // highlight on the first
764 bool LCursor::erase()
766 autocorrect() = false;
771 lyx::cap::selDel(*this);
775 // delete empty cells if possible
776 if (pos() == lastpos() && inset().idxDelete(idx()))
779 // special behaviour when in last position of cell
780 if (pos() == lastpos()) {
781 bool one_cell = inset().nargs() == 1;
782 if (one_cell && depth() == 1 && lastpos() == 0)
788 inset().idxGlue(idx());
792 // 'clever' UI hack: only erase large items if previously slected
793 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
808 DocIterator save = *this;
812 autocorrect() = false;
820 DocIterator save = *this;
824 autocorrect() = false;
829 bool LCursor::macroModeClose()
833 MathUnknownInset * p = activeMacro();
835 string const s = p->name();
839 // do nothing if the macro name is empty
843 // prevent entering of recursive macros
844 // FIXME: this is only a weak attempt... only prevents immediate
846 string const name = s.substr(1);
847 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
848 if (macro && macro->getInsetName() == name)
849 lyxerr << "can't enter recursive macro" << endl;
851 plainInsert(createMathInset(name));
856 string LCursor::macroName()
858 return inMacroMode() ? activeMacro()->name() : string();
862 void LCursor::handleNest(MathAtom const & a, int c)
864 //lyxerr << "LCursor::handleNest: " << c << endl;
866 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
869 pushLeft(*nextInset());
873 int LCursor::targetX() const
875 if (x_target() != -1)
884 void LCursor::setTargetX()
886 // For now this is good enough. A better solution would be to
887 // avoid this rebreak by setting cursorX only after drawing
888 bottom().text()->redoParagraph(bottom().pit());
896 bool LCursor::inMacroMode() const
900 MathUnknownInset const * p = prevAtom()->asUnknownInset();
901 return p && !p->final();
905 MathUnknownInset * LCursor::activeMacro()
907 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
911 void LCursor::pullArg()
916 MathArray ar = cell();
917 if (popLeft() && inMathed()) {
919 cell().insert(pos(), ar);
922 //formula()->mutateToText();
927 void LCursor::touch()
933 DocIterator::const_iterator it = begin();
934 DocIterator::const_iterator et = end();
935 for ( ; it != et; ++it)
941 void LCursor::normalize()
943 if (idx() > lastidx()) {
944 lyxerr << "this should not really happen - 1: "
945 << idx() << ' ' << nargs()
946 << " in: " << &inset() << endl;
950 if (pos() > lastpos()) {
951 lyxerr << "this should not really happen - 2: "
952 << pos() << ' ' << lastpos() << " in idx: " << idx()
954 WriteStream wi(lyxerr, false, true);
955 inset().asMathInset()->write(wi);
962 bool LCursor::goUpDown(bool up)
964 // Be warned: The 'logic' implemented in this function is highly
965 // fragile. A distance of one pixel or a '<' vs '<=' _really
966 // matters. So fiddle around with it only if you think you know
967 // what you are doing!
973 // check if we had something else in mind, if not, this is the future goal
974 if (x_target() == -1)
979 // try neigbouring script insets
983 MathScriptInset const * p = prevAtom()->asScriptInset();
984 if (p && p->has(up)) {
986 push(*const_cast<MathScriptInset*>(p));
987 idx() = p->idxOfScript(up);
994 if (pos() != lastpos()) {
995 MathScriptInset const * p = nextAtom()->asScriptInset();
996 if (p && p->has(up)) {
997 push(*const_cast<MathScriptInset*>(p));
998 idx() = p->idxOfScript(up);
1005 // FIXME: Switch this on for more robust movement
1008 return bruteFind3(*this, xo, yo, up);
1011 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1016 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1017 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1021 // try to find an inset that knows better then we
1023 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1025 if (inset().idxUpDown(*this, up)) {
1026 //lyxerr << "idxUpDown triggered" << endl;
1027 // try to find best position within this inset
1029 setCursor(bruteFind2(*this, xo, yo));
1033 // no such inset found, just take something "above"
1035 //lyxerr << "updown: popleft failed (strange case)" << endl;
1036 int ylow = up ? 0 : yo + 1;
1037 int yhigh = up ? yo - 1 : bv().workHeight();
1038 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1041 // any improvement so far?
1042 //lyxerr << "updown: popLeft succeeded" << endl;
1046 if (up ? ynew < yo : ynew > yo)
1050 // we should not come here.
1051 BOOST_ASSERT(false);
1056 void LCursor::handleFont(string const & font)
1058 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1062 safe = lyx::cap::grabAndEraseSelection(*this);
1065 if (lastpos() != 0) {
1066 // something left in the cell
1068 // cursor in first position
1070 } else if (pos() == lastpos()) {
1071 // cursor in last position
1074 // cursor in between. split cell
1075 MathArray::iterator bt = cell().begin();
1076 MathAtom at = createMathInset(font);
1077 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1078 cell().erase(bt, bt + pos());
1083 // nothing left in the cell
1091 void LCursor::message(string const & msg) const
1093 bv().owner()->getLyXFunc().setMessage(msg);
1097 void LCursor::errorMessage(string const & msg) const
1099 bv().owner()->getLyXFunc().setErrorMessage(msg);
1103 string LCursor::selectionAsString(bool label) const
1109 Buffer const & buffer = *bv().buffer();
1110 ParagraphList const & pars = text()->paragraphs();
1112 // should be const ...
1113 pit_type startpit = selBegin().pit();
1114 pit_type endpit = selEnd().pit();
1115 size_t const startpos = selBegin().pos();
1116 size_t const endpos = selEnd().pos();
1118 if (startpit == endpit)
1119 return pars[startpit].asString(buffer, startpos, endpos, label);
1121 // First paragraph in selection
1122 string result = pars[startpit].
1123 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1125 // The paragraphs in between (if any)
1126 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1127 Paragraph const & par = pars[pit];
1128 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1131 // Last paragraph in selection
1132 result += pars[endpit].asString(buffer, 0, endpos, label);
1138 return lyx::cap::grabSelection(*this);
1144 string LCursor::currentState()
1147 std::ostringstream os;
1153 return text()->currentState(*this);
1159 string LCursor::getPossibleLabel()
1161 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1165 Encoding const * LCursor::getEncoding() const
1172 // go up until first non-0 text is hit
1173 // (innermost text is 0 in mathed)
1174 for (s = depth() - 1; s >= 0; --s)
1175 if (operator[](s).text())
1177 CursorSlice const & sl = operator[](s);
1178 LyXText const & text = *sl.text();
1179 LyXFont font = text.getPar(sl.pit()).getFont(
1180 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1181 return font.language()->encoding();
1185 void LCursor::undispatched()
1187 disp_.dispatched(false);
1191 void LCursor::dispatched()
1193 disp_.dispatched(true);
1197 void LCursor::needsUpdate()
1203 void LCursor::noUpdate()
1205 disp_.update(false);
1209 LyXFont LCursor::getFont() const
1211 // HACK. far from being perfect...
1213 // go up until first non-0 text is hit
1214 // (innermost text is 0 in mathed)
1215 for (s = depth() - 1; s >= 0; --s)
1216 if (operator[](s).text())
1218 CursorSlice const & sl = operator[](s);
1219 LyXText const & text = *sl.text();
1220 LyXFont font = text.getPar(sl.pit()).getFont(
1221 bv().buffer()->params(),
1223 outerFont(sl.pit(), text.paragraphs()));
1229 void LCursor::fixIfBroken()
1231 // find out last good level
1232 LCursor copy = *this;
1233 size_t newdepth = depth();
1234 while (!copy.empty()) {
1235 if (copy.idx() > copy.lastidx()) {
1236 lyxerr << "wrong idx " << copy.idx()
1237 << ", max is " << copy.lastidx()
1238 << " at level " << copy.depth()
1239 << ". Trying to correct this." << endl;
1240 newdepth = copy.depth() - 1;
1242 else if (copy.pit() > copy.lastpit()) {
1243 lyxerr << "wrong pit " << copy.pit()
1244 << ", max is " << copy.lastpit()
1245 << " at level " << copy.depth()
1246 << ". Trying to correct this." << endl;
1247 newdepth = copy.depth() - 1;
1249 else if (copy.pos() > copy.lastpos()) {
1250 lyxerr << "wrong pos " << copy.pos()
1251 << ", max is " << copy.lastpos()
1252 << " at level " << copy.depth()
1253 << ". Trying to correct this." << endl;
1254 newdepth = copy.depth() - 1;
1258 // shrink cursor to a size where everything is valid, possibly
1260 while (depth() > newdepth) {
1262 lyxerr << "correcting cursor to level " << depth() << endl;