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>
61 #ifndef CXX_GLOBAL_CSTD
70 positionable(DocIterator const & cursor, DocIterator const & anchor)
72 // avoid deeper nested insets when selecting
73 if (cursor.depth() > anchor.depth())
76 // anchor might be deeper, should have same path then
77 for (size_t i = 0; i < cursor.depth(); ++i)
78 if (&cursor[i].inset() != &anchor[i].inset())
81 // position should be ok.
86 // Find position closest to (x, y) in cell given by iter.
87 // Used only in mathed
88 DocIterator bruteFind2(LCursor const & c, int x, int y)
90 double best_dist = std::numeric_limits<double>::max();
97 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
98 for (size_t i = 0; ; ++i) {
101 InsetBase const * inset = &it.inset();
102 Point o = theCoords.getInsets().xy(inset);
103 inset->cursorPos(it.top(), c.boundary(), xo, yo);
104 // Convert to absolute
107 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
108 // '<=' in order to take the last possible position
109 // this is important for clicking behind \sum in e.g. '\sum_i a'
110 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
111 << " best: " << best_dist << endl;
112 if (d <= best_dist) {
124 /// moves position closest to (x, y) in given box
125 bool bruteFind(LCursor & cursor,
126 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
128 BOOST_ASSERT(!cursor.empty());
129 InsetBase & inset = cursor[0].inset();
131 CoordCache::InnerParPosCache const & cache = theCoords.getParPos().find(cursor.bottom().text())->second;
132 // Get an iterator on the first paragraph in the cache
133 DocIterator it(inset);
134 it.push_back(CursorSlice(inset));
135 it.pit() = cache.begin()->first;
136 // Get an iterator after the last paragraph in the cache
137 DocIterator et(inset);
138 et.push_back(CursorSlice(inset));
139 et.pit() = boost::prior(cache.end())->first;
140 if (et.pit() >= et.lastpit())
141 et = doc_iterator_end(inset);
145 double best_dist = std::numeric_limits<double>::max();;
146 DocIterator best_cursor = et;
148 for ( ; it != et; it.forwardPos(true)) {
149 // avoid invalid nesting when selecting
150 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
151 Point p = bv_funcs::getPos(it, false);
154 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
155 double const dx = xo - x;
156 double const dy = yo - y;
157 double const d = dx * dx + dy * dy;
158 // '<=' in order to take the last possible position
159 // this is important for clicking behind \sum in e.g. '\sum_i a'
160 if (d <= best_dist) {
161 // lyxerr << "*" << endl;
169 if (best_cursor != et) {
170 cursor.setCursor(best_cursor);
178 /// moves position closest to (x, y) in given box
179 bool bruteFind3(LCursor & cur, int x, int y, bool up)
181 BufferView & bv = cur.bv();
182 int ylow = up ? 0 : y + 1;
183 int yhigh = up ? y - 1 : bv.workHeight();
185 int xhigh = bv.workWidth();
187 // FIXME: bit more work needed to get 'from' and 'to' right.
188 pit_type from = cur.bottom().pit();
189 //pit_type to = cur.bottom().pit();
190 //lyxerr << "Pit start: " << from << endl;
192 //lyxerr << "bruteFind3: x: " << x << " y: " << y
193 // << " xlow: " << xlow << " xhigh: " << xhigh
194 // << " ylow: " << ylow << " yhigh: " << yhigh
196 InsetBase & inset = bv.buffer()->inset();
197 DocIterator it = doc_iterator_begin(inset);
199 DocIterator et = doc_iterator_end(inset);
201 double best_dist = std::numeric_limits<double>::max();
202 DocIterator best_cursor = et;
204 for ( ; it != et; it.forwardPos()) {
205 // avoid invalid nesting when selecting
206 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
207 && (!cur.selection() || positionable(it, cur.anchor_))) {
208 Point p = bv_funcs::getPos(it, false);
211 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
212 double const dx = xo - x;
213 double const dy = yo - y;
214 double const d = dx * dx + dy * dy;
215 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
216 // << " dx: " << dx << " dy: " << dy
217 // << " idx: " << it.idx() << " pos: " << it.pos()
220 // '<=' in order to take the last possible position
221 // this is important for clicking behind \sum in e.g. '\sum_i a'
222 if (d <= best_dist) {
223 //lyxerr << "*" << endl;
231 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
232 if (best_cursor == et)
234 cur.setCursor(best_cursor);
241 // be careful: this is called from the bv's constructor, too, so
242 // bv functions are not yet available!
243 LCursor::LCursor(BufferView & bv)
244 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
245 selection_(false), mark_(false), logicalpos_(false)
249 void LCursor::reset(InsetBase & inset)
252 push_back(CursorSlice(inset));
253 anchor_ = DocIterator(inset);
260 // this (intentionally) does neither touch anchor nor selection status
261 void LCursor::setCursor(DocIterator const & cur)
263 DocIterator::operator=(cur);
267 void LCursor::dispatch(FuncRequest const & cmd0)
269 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
270 << " cmd: " << cmd0 << '\n'
276 FuncRequest cmd = cmd0;
277 LCursor safe = *this;
279 for (; depth(); pop()) {
280 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
281 << cmd0 << endl << *this << endl;
282 BOOST_ASSERT(pos() <= lastpos());
283 BOOST_ASSERT(idx() <= lastidx());
284 BOOST_ASSERT(pit() <= lastpit());
286 // The common case is 'LFUN handled, need update', so make the
287 // LFUN handler's life easier by assuming this as default value.
288 // The handler can reset the update and val flags if necessary.
290 disp_.dispatched(true);
291 inset().dispatch(*this, cmd);
292 if (disp_.dispatched())
295 // it completely to get a 'bomb early' behaviour in case this
296 // object will be used again.
297 if (!disp_.dispatched()) {
298 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
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(*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, size_t n)
490 void LCursor::clearSelection()
499 int & LCursor::x_target()
505 int LCursor::x_target() const
511 void LCursor::clearTargetX()
518 void LCursor::info(std::ostream & os) const
520 for (int i = 1, n = depth(); i < n; ++i) {
521 operator[](i).inset().infoize(os);
525 prevInset()->infoize2(os);
526 // overwite old message
531 void LCursor::selHandle(bool sel)
533 //lyxerr << "LCursor::selHandle" << endl;
534 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 MathNestInset).
570 ///////////////////////////////////////////////////////////////////
572 #include "mathed/math_charinset.h"
573 #include "mathed/math_factory.h"
574 #include "mathed/math_gridinset.h"
575 #include "mathed/math_macroarg.h"
576 #include "mathed/math_mathmlstream.h"
577 #include "mathed/math_scriptinset.h"
578 #include "mathed/math_support.h"
579 #include "mathed/math_unknowninset.h"
581 //#define FILEDEBUG 1
584 bool LCursor::isInside(InsetBase const * p)
586 for (size_t i = 0; i != depth(); ++i)
587 if (&operator[](i).inset() == p)
593 void LCursor::leaveInset(InsetBase const & inset)
595 for (size_t i = 0; i != depth(); ++i) {
596 if (&operator[](i).inset() == &inset) {
604 bool LCursor::openable(MathAtom const & t) const
615 // we can't move into anything new during selection
616 if (depth() >= anchor_.depth())
618 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
625 void LCursor::setScreenPos(int x, int y)
628 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
633 void LCursor::plainErase()
639 void LCursor::markInsert()
641 insert(char_type(0));
645 void LCursor::markErase()
651 void LCursor::plainInsert(MathAtom const & t)
653 cell().insert(pos(), t);
658 void LCursor::insert(string const & str)
660 for_each(str.begin(), str.end(),
661 boost::bind(static_cast<void(LCursor::*)(char_type)>
662 (&LCursor::insert), this, _1));
666 void LCursor::insert(char_type c)
668 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
669 BOOST_ASSERT(!empty());
671 lyx::cap::selClearOrDel(*this);
672 insert(new MathCharInset(c));
674 text()->insertChar(*this, c);
679 void LCursor::insert(MathAtom const & t)
681 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
683 lyx::cap::selClearOrDel(*this);
688 void LCursor::insert(InsetBase * inset)
691 insert(MathAtom(inset));
693 text()->insertInset(*this, inset);
697 void LCursor::niceInsert(string const & t)
708 void LCursor::niceInsert(MathAtom const & t)
711 string const safe = lyx::cap::grabAndEraseSelection(*this);
713 // enter the new inset and move the contents of the selection if possible
716 // be careful here: don't use 'pushLeft(t)' as this we need to
717 // push the clone, not the original
718 pushLeft(*nextInset());
719 // We may not use niceInsert here (recursion)
727 void LCursor::insert(MathArray const & ar)
731 lyx::cap::eraseSelection(*this);
732 cell().insert(pos(), ar);
737 bool LCursor::backspace()
739 autocorrect() = false;
742 lyx::cap::selDel(*this);
747 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
754 MathUnknownInset * p = activeMacro();
755 if (p->name().size() > 1) {
756 p->setName(p->name().substr(0, p->name().size() - 1));
761 if (pos() != 0 && prevAtom()->nargs() > 0) {
762 // let's require two backspaces for 'big stuff' and
763 // highlight on the first
775 bool LCursor::erase()
777 autocorrect() = false;
782 lyx::cap::selDel(*this);
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 // 'clever' UI hack: only erase large items if previously slected
804 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
819 DocIterator save = *this;
823 autocorrect() = false;
831 DocIterator save = *this;
835 autocorrect() = false;
840 bool LCursor::macroModeClose()
844 MathUnknownInset * p = activeMacro();
846 string const s = p->name();
850 // do nothing if the macro name is empty
854 // prevent entering of recursive macros
855 // FIXME: this is only a weak attempt... only prevents immediate
857 string const name = s.substr(1);
858 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
859 if (macro && macro->getInsetName() == name)
860 lyxerr << "can't enter recursive macro" << endl;
862 plainInsert(createMathInset(name));
867 string LCursor::macroName()
869 return inMacroMode() ? activeMacro()->name() : string();
873 void LCursor::handleNest(MathAtom const & a, int c)
875 //lyxerr << "LCursor::handleNest: " << c << endl;
877 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
880 pushLeft(*nextInset());
884 int LCursor::targetX() const
886 if (x_target() != -1)
895 void LCursor::setTargetX()
897 // For now this is good enough. A better solution would be to
898 // avoid this rebreak by setting cursorX only after drawing
899 bottom().text()->redoParagraph(bottom().pit());
907 bool LCursor::inMacroMode() const
911 MathUnknownInset const * p = prevAtom()->asUnknownInset();
912 return p && !p->final();
916 MathUnknownInset * LCursor::activeMacro()
918 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
922 void LCursor::pullArg()
927 MathArray ar = cell();
928 if (popLeft() && inMathed()) {
930 cell().insert(pos(), ar);
933 //formula()->mutateToText();
938 void LCursor::touch()
944 DocIterator::const_iterator it = begin();
945 DocIterator::const_iterator et = end();
946 for ( ; it != et; ++it)
952 void LCursor::normalize()
954 if (idx() > lastidx()) {
955 lyxerr << "this should not really happen - 1: "
956 << idx() << ' ' << nargs()
957 << " in: " << &inset() << endl;
961 if (pos() > lastpos()) {
962 lyxerr << "this should not really happen - 2: "
963 << pos() << ' ' << lastpos() << " in idx: " << idx()
965 WriteStream wi(lyxerr, false, true);
966 inset().asMathInset()->write(wi);
973 bool LCursor::goUpDown(bool up)
975 // Be warned: The 'logic' implemented in this function is highly
976 // fragile. A distance of one pixel or a '<' vs '<=' _really
977 // matters. So fiddle around with it only if you think you know
978 // what you are doing!
984 // check if we had something else in mind, if not, this is the future goal
985 if (x_target() == -1)
990 // try neigbouring script insets
994 MathScriptInset const * p = prevAtom()->asScriptInset();
995 if (p && p->has(up)) {
997 push(*const_cast<MathScriptInset*>(p));
998 idx() = p->idxOfScript(up);
1005 if (pos() != lastpos()) {
1006 MathScriptInset const * p = nextAtom()->asScriptInset();
1007 if (p && p->has(up)) {
1008 push(*const_cast<MathScriptInset*>(p));
1009 idx() = p->idxOfScript(up);
1016 // FIXME: Switch this on for more robust movement
1019 return bruteFind3(*this, xo, yo, up);
1022 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1027 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1028 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1032 // try to find an inset that knows better then we
1034 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1036 if (inset().idxUpDown(*this, up)) {
1037 //lyxerr << "idxUpDown triggered" << endl;
1038 // try to find best position within this inset
1040 setCursor(bruteFind2(*this, xo, yo));
1044 // no such inset found, just take something "above"
1046 //lyxerr << "updown: popleft failed (strange case)" << endl;
1047 int ylow = up ? 0 : yo + 1;
1048 int yhigh = up ? yo - 1 : bv().workHeight();
1049 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1052 // any improvement so far?
1053 //lyxerr << "updown: popLeft succeeded" << endl;
1057 if (up ? ynew < yo : ynew > yo)
1061 // we should not come here.
1062 BOOST_ASSERT(false);
1067 void LCursor::handleFont(string const & font)
1069 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1073 safe = lyx::cap::grabAndEraseSelection(*this);
1076 if (lastpos() != 0) {
1077 // something left in the cell
1079 // cursor in first position
1081 } else if (pos() == lastpos()) {
1082 // cursor in last position
1085 // cursor in between. split cell
1086 MathArray::iterator bt = cell().begin();
1087 MathAtom at = createMathInset(font);
1088 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1089 cell().erase(bt, bt + pos());
1094 // nothing left in the cell
1102 void LCursor::message(string const & msg) const
1104 bv().owner()->getLyXFunc().setMessage(msg);
1108 void LCursor::errorMessage(string const & msg) const
1110 bv().owner()->getLyXFunc().setErrorMessage(msg);
1114 string LCursor::selectionAsString(bool label) const
1120 Buffer const & buffer = *bv().buffer();
1121 ParagraphList const & pars = text()->paragraphs();
1123 // should be const ...
1124 pit_type startpit = selBegin().pit();
1125 pit_type endpit = selEnd().pit();
1126 size_t const startpos = selBegin().pos();
1127 size_t const endpos = selEnd().pos();
1129 if (startpit == endpit)
1130 return pars[startpit].asString(buffer, startpos, endpos, label);
1132 // First paragraph in selection
1133 string result = pars[startpit].
1134 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1136 // The paragraphs in between (if any)
1137 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1138 Paragraph const & par = pars[pit];
1139 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1142 // Last paragraph in selection
1143 result += pars[endpit].asString(buffer, 0, endpos, label);
1149 return lyx::cap::grabSelection(*this);
1155 string LCursor::currentState()
1158 std::ostringstream os;
1164 return text()->currentState(*this);
1170 string LCursor::getPossibleLabel()
1172 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1176 Encoding const * LCursor::getEncoding() const
1183 // go up until first non-0 text is hit
1184 // (innermost text is 0 in mathed)
1185 for (s = depth() - 1; s >= 0; --s)
1186 if (operator[](s).text())
1188 CursorSlice const & sl = operator[](s);
1189 LyXText const & text = *sl.text();
1190 LyXFont font = text.getPar(sl.pit()).getFont(
1191 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1192 return font.language()->encoding();
1196 void LCursor::undispatched()
1198 disp_.dispatched(false);
1202 void LCursor::dispatched()
1204 disp_.dispatched(true);
1208 void LCursor::needsUpdate()
1214 void LCursor::noUpdate()
1216 disp_.update(false);
1220 LyXFont LCursor::getFont() const
1222 // HACK. far from being perfect...
1224 // go up until first non-0 text is hit
1225 // (innermost text is 0 in mathed)
1226 for (s = depth() - 1; s >= 0; --s)
1227 if (operator[](s).text())
1229 CursorSlice const & sl = operator[](s);
1230 LyXText const & text = *sl.text();
1231 LyXFont font = text.getPar(sl.pit()).getFont(
1232 bv().buffer()->params(),
1234 outerFont(sl.pit(), text.paragraphs()));
1240 void LCursor::fixIfBroken()
1242 // find out last good level
1243 LCursor copy = *this;
1244 size_t newdepth = depth();
1245 while (!copy.empty()) {
1246 if (copy.idx() > copy.lastidx()) {
1247 lyxerr << "wrong idx " << copy.idx()
1248 << ", max is " << copy.lastidx()
1249 << " at level " << copy.depth()
1250 << ". Trying to correct this." << endl;
1251 newdepth = copy.depth() - 1;
1253 else if (copy.pit() > copy.lastpit()) {
1254 lyxerr << "wrong pit " << copy.pit()
1255 << ", max is " << copy.lastpit()
1256 << " at level " << copy.depth()
1257 << ". Trying to correct this." << endl;
1258 newdepth = copy.depth() - 1;
1260 else if (copy.pos() > copy.lastpos()) {
1261 lyxerr << "wrong pos " << copy.pos()
1262 << ", max is " << copy.lastpos()
1263 << " at level " << copy.depth()
1264 << ". Trying to correct this." << endl;
1265 newdepth = copy.depth() - 1;
1269 // shrink cursor to a size where everything is valid, possibly
1271 while (depth() > newdepth) {
1273 lyxerr << "correcting cursor to level " << depth() << endl;