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::paste(string const & data)
385 dispatch(FuncRequest(LFUN_PASTE, data));
389 void LCursor::resetAnchor()
396 bool LCursor::posLeft()
405 bool LCursor::posRight()
407 if (pos() == lastpos())
414 CursorSlice LCursor::anchor() const
416 BOOST_ASSERT(anchor_.depth() >= depth());
417 CursorSlice normal = anchor_[depth() - 1];
418 if (depth() < anchor_.depth() && top() <= normal) {
419 // anchor is behind cursor -> move anchor behind the inset
426 CursorSlice LCursor::selBegin() const
430 return anchor() < top() ? anchor() : top();
434 CursorSlice LCursor::selEnd() const
438 return anchor() > top() ? anchor() : top();
442 DocIterator LCursor::selectionBegin() const
446 DocIterator di = (anchor() < top() ? anchor_ : *this);
452 DocIterator LCursor::selectionEnd() const
456 DocIterator di = (anchor() > top() ? anchor_ : *this);
457 if (di.depth() > depth()) {
465 void LCursor::setSelection()
468 // A selection with no contents is not a selection
470 #warning doesnt look ok
472 if (pit() == anchor().pit() && pos() == anchor().pos())
477 void LCursor::setSelection(DocIterator const & where, size_t n)
486 void LCursor::clearSelection()
495 int & LCursor::x_target()
501 int LCursor::x_target() const
507 void LCursor::clearTargetX()
514 void LCursor::info(std::ostream & os) const
516 for (int i = 1, n = depth(); i < n; ++i) {
517 operator[](i).inset().infoize(os);
521 prevInset()->infoize2(os);
522 // overwite old message
527 void LCursor::selHandle(bool sel)
529 //lyxerr << "LCursor::selHandle" << endl;
530 if (sel == selection())
538 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
540 os << "\n cursor: | anchor:\n";
541 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
542 os << " " << cur[i] << " | ";
543 if (i < cur.anchor_.depth())
544 os << cur.anchor_[i];
546 os << "-------------------------------";
549 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
550 os << "------------------------------- | " << cur.anchor_[i] << "\n";
552 os << " selection: " << cur.selection_
553 << " x_target: " << cur.x_target_ << endl;
560 ///////////////////////////////////////////////////////////////////
562 // The part below is the non-integrated rest of the original math
563 // cursor. This should be either generalized for texted or moved
564 // back to mathed (in most cases to MathNestInset).
566 ///////////////////////////////////////////////////////////////////
568 #include "mathed/math_charinset.h"
569 #include "mathed/math_factory.h"
570 #include "mathed/math_gridinset.h"
571 #include "mathed/math_macroarg.h"
572 #include "mathed/math_mathmlstream.h"
573 #include "mathed/math_scriptinset.h"
574 #include "mathed/math_support.h"
575 #include "mathed/math_unknowninset.h"
577 //#define FILEDEBUG 1
580 bool LCursor::isInside(InsetBase const * p)
582 for (size_t i = 0; i != depth(); ++i)
583 if (&operator[](i).inset() == p)
589 void LCursor::leaveInset(InsetBase const & inset)
591 for (size_t i = 0; i != depth(); ++i) {
592 if (&operator[](i).inset() == &inset) {
600 bool LCursor::openable(MathAtom const & t) const
611 // we can't move into anything new during selection
612 if (depth() >= anchor_.depth())
614 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
621 void LCursor::setScreenPos(int x, int y)
624 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
629 void LCursor::plainErase()
635 void LCursor::markInsert()
641 void LCursor::markErase()
647 void LCursor::plainInsert(MathAtom const & t)
649 cell().insert(pos(), t);
654 void LCursor::insert(string const & str)
656 for_each(str.begin(), str.end(),
657 boost::bind(static_cast<void(LCursor::*)(char)>
658 (&LCursor::insert), this, _1));
662 void LCursor::insert(char c)
664 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
665 BOOST_ASSERT(!empty());
667 lyx::cap::selClearOrDel(*this);
668 insert(new MathCharInset(c));
670 text()->insertChar(*this, c);
675 void LCursor::insert(MathAtom const & t)
677 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
679 lyx::cap::selClearOrDel(*this);
684 void LCursor::insert(InsetBase * inset)
687 insert(MathAtom(inset));
689 text()->insertInset(*this, inset);
693 void LCursor::niceInsert(string const & t)
704 void LCursor::niceInsert(MathAtom const & t)
707 string const safe = lyx::cap::grabAndEraseSelection(*this);
709 // enter the new inset and move the contents of the selection if possible
712 // be careful here: don't use 'pushLeft(t)' as this we need to
713 // push the clone, not the original
714 pushLeft(*nextInset());
720 void LCursor::insert(MathArray const & ar)
724 lyx::cap::eraseSelection(*this);
725 cell().insert(pos(), ar);
730 bool LCursor::backspace()
732 autocorrect() = false;
735 lyx::cap::selDel(*this);
740 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
747 MathUnknownInset * p = activeMacro();
748 if (p->name().size() > 1) {
749 p->setName(p->name().substr(0, p->name().size() - 1));
754 if (pos() != 0 && prevAtom()->nargs() > 0) {
755 // let's require two backspaces for 'big stuff' and
756 // highlight on the first
768 bool LCursor::erase()
770 autocorrect() = false;
775 lyx::cap::selDel(*this);
779 // delete empty cells if possible
780 if (pos() == lastpos() && inset().idxDelete(idx()))
783 // special behaviour when in last position of cell
784 if (pos() == lastpos()) {
785 bool one_cell = inset().nargs() == 1;
786 if (one_cell && depth() == 1 && lastpos() == 0)
792 inset().idxGlue(idx());
796 // 'clever' UI hack: only erase large items if previously slected
797 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
812 DocIterator save = *this;
816 autocorrect() = false;
824 DocIterator save = *this;
828 autocorrect() = false;
833 bool LCursor::macroModeClose()
837 MathUnknownInset * p = activeMacro();
839 string const s = p->name();
843 // do nothing if the macro name is empty
847 // prevent entering of recursive macros
848 // FIXME: this is only a weak attempt... only prevents immediate
850 string const name = s.substr(1);
851 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
852 if (macro && macro->getInsetName() == name)
853 lyxerr << "can't enter recursive macro" << endl;
855 plainInsert(createMathInset(name));
860 string LCursor::macroName()
862 return inMacroMode() ? activeMacro()->name() : string();
866 void LCursor::handleNest(MathAtom const & a, int c)
868 //lyxerr << "LCursor::handleNest: " << c << endl;
870 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
873 pushLeft(*nextInset());
877 int LCursor::targetX() const
879 if (x_target() != -1)
888 void LCursor::setTargetX()
890 // For now this is good enough. A better solution would be to
891 // avoid this rebreak by setting cursorX only after drawing
892 bottom().text()->redoParagraph(bottom().pit());
900 bool LCursor::inMacroMode() const
904 MathUnknownInset const * p = prevAtom()->asUnknownInset();
905 return p && !p->final();
909 MathUnknownInset * LCursor::activeMacro()
911 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
915 void LCursor::pullArg()
920 MathArray ar = cell();
921 if (popLeft() && inMathed()) {
923 cell().insert(pos(), ar);
926 //formula()->mutateToText();
931 void LCursor::touch()
937 DocIterator::const_iterator it = begin();
938 DocIterator::const_iterator et = end();
939 for ( ; it != et; ++it)
945 void LCursor::normalize()
947 if (idx() > lastidx()) {
948 lyxerr << "this should not really happen - 1: "
949 << idx() << ' ' << nargs()
950 << " in: " << &inset() << endl;
954 if (pos() > lastpos()) {
955 lyxerr << "this should not really happen - 2: "
956 << pos() << ' ' << lastpos() << " in idx: " << idx()
958 WriteStream wi(lyxerr, false, true);
959 inset().asMathInset()->write(wi);
966 bool LCursor::goUpDown(bool up)
968 // Be warned: The 'logic' implemented in this function is highly
969 // fragile. A distance of one pixel or a '<' vs '<=' _really
970 // matters. So fiddle around with it only if you think you know
971 // what you are doing!
977 // check if we had something else in mind, if not, this is the future goal
978 if (x_target() == -1)
983 // try neigbouring script insets
987 MathScriptInset const * p = prevAtom()->asScriptInset();
988 if (p && p->has(up)) {
990 push(*const_cast<MathScriptInset*>(p));
991 idx() = p->idxOfScript(up);
998 if (pos() != lastpos()) {
999 MathScriptInset const * p = nextAtom()->asScriptInset();
1000 if (p && p->has(up)) {
1001 push(*const_cast<MathScriptInset*>(p));
1002 idx() = p->idxOfScript(up);
1009 // FIXME: Switch this on for more robust movement
1012 return bruteFind3(*this, xo, yo, up);
1015 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1020 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1021 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1025 // try to find an inset that knows better then we
1027 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1029 if (inset().idxUpDown(*this, up)) {
1030 //lyxerr << "idxUpDown triggered" << endl;
1031 // try to find best position within this inset
1033 setCursor(bruteFind2(*this, xo, yo));
1037 // no such inset found, just take something "above"
1039 //lyxerr << "updown: popleft failed (strange case)" << endl;
1040 int ylow = up ? 0 : yo + 1;
1041 int yhigh = up ? yo - 1 : bv().workHeight();
1042 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1045 // any improvement so far?
1046 //lyxerr << "updown: popLeft succeeded" << endl;
1050 if (up ? ynew < yo : ynew > yo)
1054 // we should not come here.
1055 BOOST_ASSERT(false);
1060 void LCursor::handleFont(string const & font)
1062 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1066 safe = lyx::cap::grabAndEraseSelection(*this);
1069 if (lastpos() != 0) {
1070 // something left in the cell
1072 // cursor in first position
1074 } else if (pos() == lastpos()) {
1075 // cursor in last position
1078 // cursor in between. split cell
1079 MathArray::iterator bt = cell().begin();
1080 MathAtom at = createMathInset(font);
1081 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1082 cell().erase(bt, bt + pos());
1087 // nothing left in the cell
1095 void LCursor::message(string const & msg) const
1097 bv().owner()->getLyXFunc().setMessage(msg);
1101 void LCursor::errorMessage(string const & msg) const
1103 bv().owner()->getLyXFunc().setErrorMessage(msg);
1107 string LCursor::selectionAsString(bool label) const
1113 Buffer const & buffer = *bv().buffer();
1114 ParagraphList const & pars = text()->paragraphs();
1116 // should be const ...
1117 pit_type startpit = selBegin().pit();
1118 pit_type endpit = selEnd().pit();
1119 size_t const startpos = selBegin().pos();
1120 size_t const endpos = selEnd().pos();
1122 if (startpit == endpit)
1123 return pars[startpit].asString(buffer, startpos, endpos, label);
1125 // First paragraph in selection
1126 string result = pars[startpit].
1127 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1129 // The paragraphs in between (if any)
1130 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1131 Paragraph const & par = pars[pit];
1132 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1135 // Last paragraph in selection
1136 result += pars[endpit].asString(buffer, 0, endpos, label);
1142 return lyx::cap::grabSelection(*this);
1148 string LCursor::currentState()
1151 std::ostringstream os;
1157 return text()->currentState(*this);
1163 string LCursor::getPossibleLabel()
1165 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1169 Encoding const * LCursor::getEncoding() const
1176 // go up until first non-0 text is hit
1177 // (innermost text is 0 in mathed)
1178 for (s = depth() - 1; s >= 0; --s)
1179 if (operator[](s).text())
1181 CursorSlice const & sl = operator[](s);
1182 LyXText const & text = *sl.text();
1183 LyXFont font = text.getPar(sl.pit()).getFont(
1184 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1185 return font.language()->encoding();
1189 void LCursor::undispatched()
1191 disp_.dispatched(false);
1195 void LCursor::dispatched()
1197 disp_.dispatched(true);
1201 void LCursor::needsUpdate()
1207 void LCursor::noUpdate()
1209 disp_.update(false);
1213 LyXFont LCursor::getFont() const
1215 // HACK. far from being perfect...
1217 // go up until first non-0 text is hit
1218 // (innermost text is 0 in mathed)
1219 for (s = depth() - 1; s >= 0; --s)
1220 if (operator[](s).text())
1222 CursorSlice const & sl = operator[](s);
1223 LyXText const & text = *sl.text();
1224 LyXFont font = text.getPar(sl.pit()).getFont(
1225 bv().buffer()->params(),
1227 outerFont(sl.pit(), text.paragraphs()));
1233 void LCursor::fixIfBroken()
1235 // find out last good level
1236 LCursor copy = *this;
1237 size_t newdepth = depth();
1238 while (!copy.empty()) {
1239 if (copy.idx() > copy.lastidx()) {
1240 lyxerr << "wrong idx " << copy.idx()
1241 << ", max is " << copy.lastidx()
1242 << " at level " << copy.depth()
1243 << ". Trying to correct this." << endl;
1244 newdepth = copy.depth() - 1;
1246 else if (copy.pit() > copy.lastpit()) {
1247 lyxerr << "wrong pit " << copy.pit()
1248 << ", max is " << copy.lastpit()
1249 << " at level " << copy.depth()
1250 << ". Trying to correct this." << endl;
1251 newdepth = copy.depth() - 1;
1253 else if (copy.pos() > copy.lastpos()) {
1254 lyxerr << "wrong pos " << copy.pos()
1255 << ", max is " << copy.lastpos()
1256 << " at level " << copy.depth()
1257 << ". Trying to correct this." << endl;
1258 newdepth = copy.depth() - 1;
1262 // shrink cursor to a size where everything is valid, possibly
1264 while (depth() > newdepth) {
1266 lyxerr << "correcting cursor to level " << depth() << endl;