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/MathData.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathScript.h"
41 #include "mathed/MathMacroTable.h"
42 #include "mathed/MathParser.h"
44 #include "support/limited_stack.h"
46 #include <boost/assert.hpp>
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
58 #ifndef CXX_GLOBAL_CSTD
67 positionable(DocIterator const & cursor, DocIterator const & anchor)
69 // avoid deeper nested insets when selecting
70 if (cursor.depth() > anchor.depth())
73 // anchor might be deeper, should have same path then
74 for (size_t i = 0; i < cursor.depth(); ++i)
75 if (&cursor[i].inset() != &anchor[i].inset())
78 // position should be ok.
83 // Find position closest to (x, y) in cell given by iter.
84 // Used only in mathed
85 DocIterator bruteFind2(LCursor const & c, int x, int y)
87 double best_dist = std::numeric_limits<double>::max();
94 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
95 for (size_t i = 0; ; ++i) {
98 InsetBase const * inset = &it.inset();
99 Point o = c.bv().coordCache().getInsets().xy(inset);
100 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
101 // Convert to absolute
104 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
105 // '<=' in order to take the last possible position
106 // this is important for clicking behind \sum in e.g. '\sum_i a'
107 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
108 << " best: " << best_dist << endl;
109 if (d <= best_dist) {
121 /// moves position closest to (x, y) in given box
122 bool bruteFind(LCursor & cursor,
123 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
125 BOOST_ASSERT(!cursor.empty());
126 InsetBase & inset = cursor[0].inset();
127 BufferView & bv = cursor.bv();
129 CoordCache::InnerParPosCache const & cache =
130 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
131 // Get an iterator on the first paragraph in the cache
132 DocIterator it(inset);
133 it.push_back(CursorSlice(inset));
134 it.pit() = cache.begin()->first;
135 // Get an iterator after the last paragraph in the cache
136 DocIterator et(inset);
137 et.push_back(CursorSlice(inset));
138 et.pit() = boost::prior(cache.end())->first;
139 if (et.pit() >= et.lastpit())
140 et = doc_iterator_end(inset);
144 double best_dist = std::numeric_limits<double>::max();;
145 DocIterator best_cursor = et;
147 for ( ; it != et; it.forwardPos(true)) {
148 // avoid invalid nesting when selecting
149 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
150 Point p = bv_funcs::getPos(bv, it, false);
153 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
154 double const dx = xo - x;
155 double const dy = yo - y;
156 double const d = dx * dx + dy * dy;
157 // '<=' in order to take the last possible position
158 // this is important for clicking behind \sum in e.g. '\sum_i a'
159 if (d <= best_dist) {
160 // lyxerr << "*" << endl;
168 if (best_cursor != et) {
169 cursor.setCursor(best_cursor);
177 /// moves position closest to (x, y) in given box
178 bool bruteFind3(LCursor & cur, int x, int y, bool up)
180 BufferView & bv = cur.bv();
181 int ylow = up ? 0 : y + 1;
182 int yhigh = up ? y - 1 : bv.workHeight();
184 int xhigh = bv.workWidth();
186 // FIXME: bit more work needed to get 'from' and 'to' right.
187 pit_type from = cur.bottom().pit();
188 //pit_type to = cur.bottom().pit();
189 //lyxerr << "Pit start: " << from << endl;
191 //lyxerr << "bruteFind3: x: " << x << " y: " << y
192 // << " xlow: " << xlow << " xhigh: " << xhigh
193 // << " ylow: " << ylow << " yhigh: " << yhigh
195 InsetBase & inset = bv.buffer()->inset();
196 DocIterator it = doc_iterator_begin(inset);
198 DocIterator et = doc_iterator_end(inset);
200 double best_dist = std::numeric_limits<double>::max();
201 DocIterator best_cursor = et;
203 for ( ; it != et; it.forwardPos()) {
204 // avoid invalid nesting when selecting
205 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
206 && (!cur.selection() || positionable(it, cur.anchor_))) {
207 Point p = bv_funcs::getPos(bv, it, false);
210 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
211 double const dx = xo - x;
212 double const dy = yo - y;
213 double const d = dx * dx + dy * dy;
214 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
215 // << " dx: " << dx << " dy: " << dy
216 // << " idx: " << it.idx() << " pos: " << it.pos()
219 // '<=' in order to take the last possible position
220 // this is important for clicking behind \sum in e.g. '\sum_i a'
221 if (d <= best_dist) {
222 //lyxerr << "*" << endl;
230 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
231 if (best_cursor == et)
233 cur.setCursor(best_cursor);
240 // be careful: this is called from the bv's constructor, too, so
241 // bv functions are not yet available!
242 LCursor::LCursor(BufferView & bv)
243 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
244 selection_(false), mark_(false), logicalpos_(false)
248 void LCursor::reset(InsetBase & inset)
251 push_back(CursorSlice(inset));
252 anchor_ = DocIterator(inset);
259 // this (intentionally) does neither touch anchor nor selection status
260 void LCursor::setCursor(DocIterator const & cur)
262 DocIterator::operator=(cur);
266 void LCursor::dispatch(FuncRequest const & cmd0)
268 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
269 << " cmd: " << cmd0 << '\n'
275 FuncRequest cmd = cmd0;
276 LCursor safe = *this;
278 for (; depth(); pop()) {
279 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
280 << cmd0 << endl << *this << endl;
281 BOOST_ASSERT(pos() <= lastpos());
282 BOOST_ASSERT(idx() <= lastidx());
283 BOOST_ASSERT(pit() <= lastpit());
285 // The common case is 'LFUN handled, need update', so make the
286 // LFUN handler's life easier by assuming this as default value.
287 // The handler can reset the update and val flags if necessary.
288 disp_.update(Update::FitCursor | Update::Force);
289 disp_.dispatched(true);
290 inset().dispatch(*this, cmd);
291 if (disp_.dispatched())
294 // it completely to get a 'bomb early' behaviour in case this
295 // object will be used again.
296 if (!disp_.dispatched()) {
297 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
299 disp_.update(Update::None);
300 disp_.dispatched(false);
305 DispatchResult LCursor::result() const
311 BufferView & LCursor::bv() const
318 Buffer & LCursor::buffer() const
321 BOOST_ASSERT(bv_->buffer());
322 return *bv_->buffer();
328 BOOST_ASSERT(depth() >= 1);
333 void LCursor::push(InsetBase & p)
335 push_back(CursorSlice(p));
339 void LCursor::pushLeft(InsetBase & p)
341 BOOST_ASSERT(!empty());
342 //lyxerr << "Entering inset " << t << " left" << endl;
348 bool LCursor::popLeft()
350 BOOST_ASSERT(!empty());
351 //lyxerr << "Leaving inset to the left" << endl;
352 inset().notifyCursorLeaves(*this);
360 bool LCursor::popRight()
362 BOOST_ASSERT(!empty());
363 //lyxerr << "Leaving inset to the right" << endl;
364 inset().notifyCursorLeaves(*this);
373 int LCursor::currentMode()
375 BOOST_ASSERT(!empty());
376 for (int i = depth() - 1; i >= 0; --i) {
377 int res = operator[](i).inset().currentMode();
378 if (res != InsetBase::UNDECIDED_MODE)
381 return InsetBase::TEXT_MODE;
385 void LCursor::getPos(int & x, int & y) const
387 Point p = bv_funcs::getPos(bv(), *this, boundary());
393 void LCursor::resetAnchor()
400 bool LCursor::posLeft()
409 bool LCursor::posRight()
411 if (pos() == lastpos())
418 CursorSlice LCursor::anchor() const
420 BOOST_ASSERT(anchor_.depth() >= depth());
421 CursorSlice normal = anchor_[depth() - 1];
422 if (depth() < anchor_.depth() && top() <= normal) {
423 // anchor is behind cursor -> move anchor behind the inset
430 CursorSlice LCursor::selBegin() const
434 return anchor() < top() ? anchor() : top();
438 CursorSlice LCursor::selEnd() const
442 return anchor() > top() ? anchor() : top();
446 DocIterator LCursor::selectionBegin() const
450 DocIterator di = (anchor() < top() ? anchor_ : *this);
456 DocIterator LCursor::selectionEnd() const
460 DocIterator di = (anchor() > top() ? anchor_ : *this);
461 if (di.depth() > depth()) {
469 void LCursor::setSelection()
472 // A selection with no contents is not a selection
474 #warning doesnt look ok
476 if (pit() == anchor().pit() && pos() == anchor().pos())
481 void LCursor::setSelection(DocIterator const & where, int n)
490 void LCursor::clearSelection()
498 int & LCursor::x_target()
504 int LCursor::x_target() const
510 void LCursor::clearTargetX()
517 void LCursor::info(odocstream & os) const
519 for (int i = 1, n = depth(); i < n; ++i) {
520 operator[](i).inset().infoize(os);
524 prevInset()->infoize2(os);
525 // overwite old message
530 bool LCursor::selHandle(bool sel)
532 //lyxerr << "LCursor::selHandle" << endl;
533 if (sel == selection())
542 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
544 os << "\n cursor: | anchor:\n";
545 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
546 os << " " << cur[i] << " | ";
547 if (i < cur.anchor_.depth())
548 os << cur.anchor_[i];
550 os << "-------------------------------";
553 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
554 os << "------------------------------- | " << cur.anchor_[i] << "\n";
556 os << " selection: " << cur.selection_
557 << " x_target: " << cur.x_target_ << endl;
564 ///////////////////////////////////////////////////////////////////
566 // The part below is the non-integrated rest of the original math
567 // cursor. This should be either generalized for texted or moved
568 // back to mathed (in most cases to InsetMathNest).
570 ///////////////////////////////////////////////////////////////////
572 #include "mathed/InsetMathChar.h"
573 #include "mathed/InsetMathGrid.h"
574 #include "mathed/InsetMathScript.h"
575 #include "mathed/InsetMathUnknown.h"
576 #include "mathed/MathFactory.h"
577 #include "mathed/MathMacroArgument.h"
578 #include "mathed/MathStream.h"
579 #include "mathed/MathSupport.h"
584 //#define FILEDEBUG 1
587 bool LCursor::isInside(InsetBase const * p)
589 for (size_t i = 0; i != depth(); ++i)
590 if (&operator[](i).inset() == p)
596 void LCursor::leaveInset(InsetBase const & inset)
598 for (size_t i = 0; i != depth(); ++i) {
599 if (&operator[](i).inset() == &inset) {
607 bool LCursor::openable(MathAtom const & t) const
618 // we can't move into anything new during selection
619 if (depth() >= anchor_.depth())
621 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
628 void LCursor::setScreenPos(int x, int y)
631 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
636 void LCursor::plainErase()
642 void LCursor::markInsert()
644 insert(char_type(0));
648 void LCursor::markErase()
654 void LCursor::plainInsert(MathAtom const & t)
656 cell().insert(pos(), t);
661 void LCursor::insert(docstring const & str)
663 for_each(str.begin(), str.end(),
664 boost::bind(static_cast<void(LCursor::*)(char_type)>
665 (&LCursor::insert), this, _1));
669 void LCursor::insert(char_type c)
671 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
672 BOOST_ASSERT(!empty());
674 cap::selClearOrDel(*this);
675 insert(new InsetMathChar(c));
677 text()->insertChar(*this, c);
682 void LCursor::insert(MathAtom const & t)
684 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
686 cap::selClearOrDel(*this);
691 void LCursor::insert(InsetBase * inset)
694 insert(MathAtom(inset));
696 text()->insertInset(*this, inset);
700 void LCursor::niceInsert(docstring const & t)
711 void LCursor::niceInsert(MathAtom const & t)
714 docstring const safe = cap::grabAndEraseSelection(*this);
716 // enter the new inset and move the contents of the selection if possible
719 // be careful here: don't use 'pushLeft(t)' as this we need to
720 // push the clone, not the original
721 pushLeft(*nextInset());
722 // We may not use niceInsert here (recursion)
730 void LCursor::insert(MathArray const & ar)
734 cap::eraseSelection(*this);
735 cell().insert(pos(), ar);
740 bool LCursor::backspace()
742 autocorrect() = false;
750 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
757 InsetMathUnknown * p = activeMacro();
758 if (p->name().size() > 1) {
759 p->setName(p->name().substr(0, p->name().size() - 1));
764 if (pos() != 0 && prevAtom()->nargs() > 0) {
765 // let's require two backspaces for 'big stuff' and
766 // highlight on the first
778 bool LCursor::erase()
780 autocorrect() = false;
789 // delete empty cells if possible
790 if (pos() == lastpos() && inset().idxDelete(idx()))
793 // special behaviour when in last position of cell
794 if (pos() == lastpos()) {
795 bool one_cell = inset().nargs() == 1;
796 if (one_cell && depth() == 1 && lastpos() == 0)
802 inset().idxGlue(idx());
806 // 'clever' UI hack: only erase large items if previously slected
807 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
822 DocIterator save = *this;
826 autocorrect() = false;
834 DocIterator save = *this;
838 autocorrect() = false;
843 bool LCursor::macroModeClose()
847 InsetMathUnknown * p = activeMacro();
849 docstring const s = p->name();
853 // do nothing if the macro name is empty
857 // prevent entering of recursive macros
858 // FIXME: this is only a weak attempt... only prevents immediate
860 docstring const name = s.substr(1);
861 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
862 if (macro && macro->getInsetName() == name)
863 lyxerr << "can't enter recursive macro" << endl;
865 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
866 if (in && in->interpretString(*this, s))
868 plainInsert(createInsetMath(name));
873 docstring LCursor::macroName()
875 return inMacroMode() ? activeMacro()->name() : docstring();
879 void LCursor::handleNest(MathAtom const & a, int c)
881 //lyxerr << "LCursor::handleNest: " << c << endl;
883 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
886 pushLeft(*nextInset());
890 int LCursor::targetX() const
892 if (x_target() != -1)
901 void LCursor::setTargetX()
903 // For now this is good enough. A better solution would be to
904 // avoid this rebreak by setting cursorX only after drawing
905 bottom().text()->redoParagraph(bv(), bottom().pit());
913 bool LCursor::inMacroMode() const
917 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
918 return p && !p->final();
922 InsetMathUnknown * LCursor::activeMacro()
924 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
928 void LCursor::pullArg()
933 MathArray ar = cell();
934 if (popLeft() && inMathed()) {
936 cell().insert(pos(), ar);
939 //formula()->mutateToText();
944 void LCursor::touch()
950 DocIterator::const_iterator it = begin();
951 DocIterator::const_iterator et = end();
952 for ( ; it != et; ++it)
958 void LCursor::normalize()
960 if (idx() > lastidx()) {
961 lyxerr << "this should not really happen - 1: "
962 << idx() << ' ' << nargs()
963 << " in: " << &inset() << endl;
967 if (pos() > lastpos()) {
968 lyxerr << "this should not really happen - 2: "
969 << pos() << ' ' << lastpos() << " in idx: " << idx()
972 WriteStream wi(os, false, true);
973 inset().asInsetMath()->write(wi);
974 lyxerr << to_utf8(os.str()) << endl;
980 bool LCursor::goUpDown(bool up)
982 // Be warned: The 'logic' implemented in this function is highly
983 // fragile. A distance of one pixel or a '<' vs '<=' _really
984 // matters. So fiddle around with it only if you think you know
985 // what you are doing!
991 // check if we had something else in mind, if not, this is the future
993 if (x_target() == -1)
998 // try neigbouring script insets
1002 InsetMathScript const * p = prevAtom()->asScriptInset();
1003 if (p && p->has(up)) {
1005 push(*const_cast<InsetMathScript*>(p));
1006 idx() = p->idxOfScript(up);
1013 if (pos() != lastpos()) {
1014 InsetMathScript const * p = nextAtom()->asScriptInset();
1015 if (p && p->has(up)) {
1016 push(*const_cast<InsetMathScript*>(p));
1017 idx() = p->idxOfScript(up);
1024 // FIXME: Switch this on for more robust movement
1027 return bruteFind3(*this, xo, yo, up);
1030 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1035 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1036 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1040 // try to find an inset that knows better then we
1042 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1044 if (inset().idxUpDown(*this, up)) {
1045 //lyxerr << "idxUpDown triggered" << endl;
1046 // try to find best position within this inset
1048 setCursor(bruteFind2(*this, xo, yo));
1052 // no such inset found, just take something "above"
1054 //lyxerr << "updown: popleft failed (strange case)" << endl;
1055 int ylow = up ? 0 : yo + 1;
1056 int yhigh = up ? yo - 1 : bv().workHeight();
1057 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1060 // any improvement so far?
1061 //lyxerr << "updown: popLeft succeeded" << endl;
1065 if (up ? ynew < yo : ynew > yo)
1069 // we should not come here.
1070 BOOST_ASSERT(false);
1075 void LCursor::handleFont(string const & font)
1077 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1081 safe = cap::grabAndEraseSelection(*this);
1084 if (lastpos() != 0) {
1085 // something left in the cell
1087 // cursor in first position
1089 } else if (pos() == lastpos()) {
1090 // cursor in last position
1093 // cursor in between. split cell
1094 MathArray::iterator bt = cell().begin();
1095 MathAtom at = createInsetMath(from_utf8(font));
1096 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1097 cell().erase(bt, bt + pos());
1102 // nothing left in the cell
1110 void LCursor::message(docstring const & msg) const
1112 theLyXFunc().setMessage(msg);
1116 void LCursor::errorMessage(docstring const & msg) const
1118 theLyXFunc().setErrorMessage(msg);
1122 docstring LCursor::selectionAsString(bool label) const
1128 Buffer const & buffer = *bv().buffer();
1129 ParagraphList const & pars = text()->paragraphs();
1131 // should be const ...
1132 pit_type startpit = selBegin().pit();
1133 pit_type endpit = selEnd().pit();
1134 size_t const startpos = selBegin().pos();
1135 size_t const endpos = selEnd().pos();
1137 if (startpit == endpit)
1138 return pars[startpit].asString(buffer, startpos, endpos, label);
1140 // First paragraph in selection
1141 docstring result = pars[startpit].
1142 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1144 // The paragraphs in between (if any)
1145 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1146 Paragraph const & par = pars[pit];
1147 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1150 // Last paragraph in selection
1151 result += pars[endpit].asString(buffer, 0, endpos, label);
1157 return cap::grabSelection(*this);
1163 string LCursor::currentState()
1166 odocstringstream os;
1168 return to_utf8(os.str());
1172 return text()->currentState(*this);
1178 string LCursor::getPossibleLabel()
1180 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1184 Encoding const * LCursor::getEncoding() const
1191 // go up until first non-0 text is hit
1192 // (innermost text is 0 in mathed)
1193 for (s = depth() - 1; s >= 0; --s)
1194 if (operator[](s).text())
1196 CursorSlice const & sl = operator[](s);
1197 LyXText const & text = *sl.text();
1198 LyXFont font = text.getPar(sl.pit()).getFont(
1199 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1200 return font.language()->encoding();
1204 void LCursor::undispatched()
1206 disp_.dispatched(false);
1210 void LCursor::dispatched()
1212 disp_.dispatched(true);
1216 void LCursor::updateFlags(Update::flags f)
1222 void LCursor::noUpdate()
1224 disp_.update(Update::None);
1228 LyXFont LCursor::getFont() const
1230 // HACK. far from being perfect...
1232 // go up until first non-0 text is hit
1233 // (innermost text is 0 in mathed)
1234 for (s = depth() - 1; s >= 0; --s)
1235 if (operator[](s).text())
1237 CursorSlice const & sl = operator[](s);
1238 LyXText const & text = *sl.text();
1239 LyXFont font = text.getPar(sl.pit()).getFont(
1240 bv().buffer()->params(),
1242 outerFont(sl.pit(), text.paragraphs()));
1248 void LCursor::fixIfBroken()
1250 // find out last good level
1251 LCursor copy = *this;
1252 size_t newdepth = depth();
1253 while (!copy.empty()) {
1254 if (copy.idx() > copy.lastidx()) {
1255 lyxerr << "wrong idx " << copy.idx()
1256 << ", max is " << copy.lastidx()
1257 << " at level " << copy.depth()
1258 << ". Trying to correct this." << endl;
1259 newdepth = copy.depth() - 1;
1261 else if (copy.pit() > copy.lastpit()) {
1262 lyxerr << "wrong pit " << copy.pit()
1263 << ", max is " << copy.lastpit()
1264 << " at level " << copy.depth()
1265 << ". Trying to correct this." << endl;
1266 newdepth = copy.depth() - 1;
1268 else if (copy.pos() > copy.lastpos()) {
1269 lyxerr << "wrong pos " << copy.pos()
1270 << ", max is " << copy.lastpos()
1271 << " at level " << copy.depth()
1272 << ". Trying to correct this." << endl;
1273 newdepth = copy.depth() - 1;
1277 // shrink cursor to a size where everything is valid, possibly
1279 while (depth() > newdepth) {
1281 lyxerr << "correcting cursor to level " << depth() << endl;