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"
42 #include "mathed/math_parser.h"
44 #include "support/limited_stack.h"
46 #include "frontends/LyXView.h"
47 #include "frontends/font_metrics.h"
49 #include <boost/assert.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/current_function.hpp>
62 #ifndef CXX_GLOBAL_CSTD
71 positionable(DocIterator const & cursor, DocIterator const & anchor)
73 // avoid deeper nested insets when selecting
74 if (cursor.depth() > anchor.depth())
77 // anchor might be deeper, should have same path then
78 for (size_t i = 0; i < cursor.depth(); ++i)
79 if (&cursor[i].inset() != &anchor[i].inset())
82 // position should be ok.
87 // Find position closest to (x, y) in cell given by iter.
88 // Used only in mathed
89 DocIterator bruteFind2(LCursor const & c, int x, int y)
91 double best_dist = std::numeric_limits<double>::max();
98 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
99 for (size_t i = 0; ; ++i) {
102 InsetBase const * inset = &it.inset();
103 Point o = theCoords.getInsets().xy(inset);
104 inset->cursorPos(it.top(), c.boundary(), xo, yo);
105 // Convert to absolute
108 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
109 // '<=' in order to take the last possible position
110 // this is important for clicking behind \sum in e.g. '\sum_i a'
111 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
112 << " best: " << best_dist << endl;
113 if (d <= best_dist) {
125 /// moves position closest to (x, y) in given box
126 bool bruteFind(LCursor & cursor,
127 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
129 BOOST_ASSERT(!cursor.empty());
130 InsetBase & inset = cursor[0].inset();
132 CoordCache::InnerParPosCache const & cache = theCoords.getParPos().find(cursor.bottom().text())->second;
133 // Get an iterator on the first paragraph in the cache
134 DocIterator it(inset);
135 it.push_back(CursorSlice(inset));
136 it.pit() = cache.begin()->first;
137 // Get an iterator after the last paragraph in the cache
138 DocIterator et(inset);
139 et.push_back(CursorSlice(inset));
140 et.pit() = boost::prior(cache.end())->first;
141 if (et.pit() >= et.lastpit())
142 et = doc_iterator_end(inset);
146 double best_dist = std::numeric_limits<double>::max();;
147 DocIterator best_cursor = et;
149 for ( ; it != et; it.forwardPos(true)) {
150 // avoid invalid nesting when selecting
151 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
152 Point p = bv_funcs::getPos(it, false);
155 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
156 double const dx = xo - x;
157 double const dy = yo - y;
158 double const d = dx * dx + dy * dy;
159 // '<=' in order to take the last possible position
160 // this is important for clicking behind \sum in e.g. '\sum_i a'
161 if (d <= best_dist) {
162 // lyxerr << "*" << endl;
170 if (best_cursor != et) {
171 cursor.setCursor(best_cursor);
179 /// moves position closest to (x, y) in given box
180 bool bruteFind3(LCursor & cur, int x, int y, bool up)
182 BufferView & bv = cur.bv();
183 int ylow = up ? 0 : y + 1;
184 int yhigh = up ? y - 1 : bv.workHeight();
186 int xhigh = bv.workWidth();
188 // FIXME: bit more work needed to get 'from' and 'to' right.
189 pit_type from = cur.bottom().pit();
190 //pit_type to = cur.bottom().pit();
191 //lyxerr << "Pit start: " << from << endl;
193 //lyxerr << "bruteFind3: x: " << x << " y: " << y
194 // << " xlow: " << xlow << " xhigh: " << xhigh
195 // << " ylow: " << ylow << " yhigh: " << yhigh
197 InsetBase & inset = bv.buffer()->inset();
198 DocIterator it = doc_iterator_begin(inset);
200 DocIterator et = doc_iterator_end(inset);
202 double best_dist = std::numeric_limits<double>::max();
203 DocIterator best_cursor = et;
205 for ( ; it != et; it.forwardPos()) {
206 // avoid invalid nesting when selecting
207 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
208 && (!cur.selection() || positionable(it, cur.anchor_))) {
209 Point p = bv_funcs::getPos(it, false);
212 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
213 double const dx = xo - x;
214 double const dy = yo - y;
215 double const d = dx * dx + dy * dy;
216 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
217 // << " dx: " << dx << " dy: " << dy
218 // << " idx: " << it.idx() << " pos: " << it.pos()
221 // '<=' in order to take the last possible position
222 // this is important for clicking behind \sum in e.g. '\sum_i a'
223 if (d <= best_dist) {
224 //lyxerr << "*" << endl;
232 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
233 if (best_cursor == et)
235 cur.setCursor(best_cursor);
242 // be careful: this is called from the bv's constructor, too, so
243 // bv functions are not yet available!
244 LCursor::LCursor(BufferView & bv)
245 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
246 selection_(false), mark_(false), logicalpos_(false)
250 void LCursor::reset(InsetBase & inset)
253 push_back(CursorSlice(inset));
254 anchor_ = DocIterator(inset);
261 // this (intentionally) does neither touch anchor nor selection status
262 void LCursor::setCursor(DocIterator const & cur)
264 DocIterator::operator=(cur);
268 void LCursor::dispatch(FuncRequest const & cmd0)
270 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
271 << " cmd: " << cmd0 << '\n'
277 FuncRequest cmd = cmd0;
278 LCursor safe = *this;
280 for (; depth(); pop()) {
281 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
282 << cmd0 << endl << *this << endl;
283 BOOST_ASSERT(pos() <= lastpos());
284 BOOST_ASSERT(idx() <= lastidx());
285 BOOST_ASSERT(pit() <= lastpit());
287 // The common case is 'LFUN handled, need update', so make the
288 // LFUN handler's life easier by assuming this as default value.
289 // The handler can reset the update and val flags if necessary.
291 disp_.dispatched(true);
292 inset().dispatch(*this, cmd);
293 if (disp_.dispatched())
296 // it completely to get a 'bomb early' behaviour in case this
297 // object will be used again.
298 if (!disp_.dispatched()) {
299 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
301 disp_.dispatched(false);
306 DispatchResult LCursor::result() const
312 BufferView & LCursor::bv() const
319 Buffer & LCursor::buffer() const
322 BOOST_ASSERT(bv_->buffer());
323 return *bv_->buffer();
329 BOOST_ASSERT(depth() >= 1);
334 void LCursor::push(InsetBase & p)
336 push_back(CursorSlice(p));
340 void LCursor::pushLeft(InsetBase & p)
342 BOOST_ASSERT(!empty());
343 //lyxerr << "Entering inset " << t << " left" << endl;
349 bool LCursor::popLeft()
351 BOOST_ASSERT(!empty());
352 //lyxerr << "Leaving inset to the left" << endl;
353 inset().notifyCursorLeaves(*this);
361 bool LCursor::popRight()
363 BOOST_ASSERT(!empty());
364 //lyxerr << "Leaving inset to the right" << endl;
365 inset().notifyCursorLeaves(*this);
374 int LCursor::currentMode()
376 BOOST_ASSERT(!empty());
377 for (int i = depth() - 1; i >= 0; --i) {
378 int res = operator[](i).inset().currentMode();
379 if (res != InsetBase::UNDECIDED_MODE)
382 return InsetBase::TEXT_MODE;
386 void LCursor::getPos(int & x, int & y) const
388 Point p = bv_funcs::getPos(*this, boundary());
394 void LCursor::resetAnchor()
401 bool LCursor::posLeft()
410 bool LCursor::posRight()
412 if (pos() == lastpos())
419 CursorSlice LCursor::anchor() const
421 BOOST_ASSERT(anchor_.depth() >= depth());
422 CursorSlice normal = anchor_[depth() - 1];
423 if (depth() < anchor_.depth() && top() <= normal) {
424 // anchor is behind cursor -> move anchor behind the inset
431 CursorSlice LCursor::selBegin() const
435 return anchor() < top() ? anchor() : top();
439 CursorSlice LCursor::selEnd() const
443 return anchor() > top() ? anchor() : top();
447 DocIterator LCursor::selectionBegin() const
451 DocIterator di = (anchor() < top() ? anchor_ : *this);
457 DocIterator LCursor::selectionEnd() const
461 DocIterator di = (anchor() > top() ? anchor_ : *this);
462 if (di.depth() > depth()) {
470 void LCursor::setSelection()
473 // A selection with no contents is not a selection
475 #warning doesnt look ok
477 if (pit() == anchor().pit() && pos() == anchor().pos())
482 void LCursor::setSelection(DocIterator const & where, size_t n)
491 void LCursor::clearSelection()
500 int & LCursor::x_target()
506 int LCursor::x_target() const
512 void LCursor::clearTargetX()
519 void LCursor::info(std::ostream & os) const
521 for (int i = 1, n = depth(); i < n; ++i) {
522 operator[](i).inset().infoize(os);
526 prevInset()->infoize2(os);
527 // overwite old message
532 void LCursor::selHandle(bool sel)
534 //lyxerr << "LCursor::selHandle" << endl;
535 if (sel == selection())
543 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
545 os << "\n cursor: | anchor:\n";
546 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
547 os << " " << cur[i] << " | ";
548 if (i < cur.anchor_.depth())
549 os << cur.anchor_[i];
551 os << "-------------------------------";
554 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
555 os << "------------------------------- | " << cur.anchor_[i] << "\n";
557 os << " selection: " << cur.selection_
558 << " x_target: " << cur.x_target_ << endl;
565 ///////////////////////////////////////////////////////////////////
567 // The part below is the non-integrated rest of the original math
568 // cursor. This should be either generalized for texted or moved
569 // back to mathed (in most cases to MathNestInset).
571 ///////////////////////////////////////////////////////////////////
573 #include "mathed/math_charinset.h"
574 #include "mathed/math_factory.h"
575 #include "mathed/math_gridinset.h"
576 #include "mathed/math_macroarg.h"
577 #include "mathed/math_mathmlstream.h"
578 #include "mathed/math_scriptinset.h"
579 #include "mathed/math_support.h"
580 #include "mathed/math_unknowninset.h"
582 //#define FILEDEBUG 1
585 bool LCursor::isInside(InsetBase const * p)
587 for (size_t i = 0; i != depth(); ++i)
588 if (&operator[](i).inset() == p)
594 void LCursor::leaveInset(InsetBase const & inset)
596 for (size_t i = 0; i != depth(); ++i) {
597 if (&operator[](i).inset() == &inset) {
605 bool LCursor::openable(MathAtom const & t) const
616 // we can't move into anything new during selection
617 if (depth() >= anchor_.depth())
619 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
626 void LCursor::setScreenPos(int x, int y)
629 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
634 void LCursor::plainErase()
640 void LCursor::markInsert()
642 insert(char_type(0));
646 void LCursor::markErase()
652 void LCursor::plainInsert(MathAtom const & t)
654 cell().insert(pos(), t);
659 void LCursor::insert(string const & str)
661 for_each(str.begin(), str.end(),
662 boost::bind(static_cast<void(LCursor::*)(char_type)>
663 (&LCursor::insert), this, _1));
667 void LCursor::insert(char_type c)
669 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
670 BOOST_ASSERT(!empty());
672 lyx::cap::selClearOrDel(*this);
673 insert(new MathCharInset(c));
675 text()->insertChar(*this, c);
680 void LCursor::insert(MathAtom const & t)
682 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
684 lyx::cap::selClearOrDel(*this);
689 void LCursor::insert(InsetBase * inset)
692 insert(MathAtom(inset));
694 text()->insertInset(*this, inset);
698 void LCursor::niceInsert(string const & t)
709 void LCursor::niceInsert(MathAtom const & t)
712 string const safe = lyx::cap::grabAndEraseSelection(*this);
714 // enter the new inset and move the contents of the selection if possible
717 // be careful here: don't use 'pushLeft(t)' as this we need to
718 // push the clone, not the original
719 pushLeft(*nextInset());
720 // We may not use niceInsert here (recursion)
728 void LCursor::insert(MathArray const & ar)
732 lyx::cap::eraseSelection(*this);
733 cell().insert(pos(), ar);
738 bool LCursor::backspace()
740 autocorrect() = false;
743 lyx::cap::selDel(*this);
748 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
755 MathUnknownInset * p = activeMacro();
756 if (p->name().size() > 1) {
757 p->setName(p->name().substr(0, p->name().size() - 1));
762 if (pos() != 0 && prevAtom()->nargs() > 0) {
763 // let's require two backspaces for 'big stuff' and
764 // highlight on the first
776 bool LCursor::erase()
778 autocorrect() = false;
783 lyx::cap::selDel(*this);
787 // delete empty cells if possible
788 if (pos() == lastpos() && inset().idxDelete(idx()))
791 // special behaviour when in last position of cell
792 if (pos() == lastpos()) {
793 bool one_cell = inset().nargs() == 1;
794 if (one_cell && depth() == 1 && lastpos() == 0)
800 inset().idxGlue(idx());
804 // 'clever' UI hack: only erase large items if previously slected
805 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
820 DocIterator save = *this;
824 autocorrect() = false;
832 DocIterator save = *this;
836 autocorrect() = false;
841 bool LCursor::macroModeClose()
845 MathUnknownInset * p = activeMacro();
847 string const s = p->name();
851 // do nothing if the macro name is empty
855 // prevent entering of recursive macros
856 // FIXME: this is only a weak attempt... only prevents immediate
858 string const name = s.substr(1);
859 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
860 if (macro && macro->getInsetName() == name)
861 lyxerr << "can't enter recursive macro" << endl;
863 MathNestInset * const in = inset().asMathInset()->asNestInset();
864 if (in && in->interpret(*this, s))
866 plainInsert(createMathInset(name));
871 string LCursor::macroName()
873 return inMacroMode() ? activeMacro()->name() : string();
877 void LCursor::handleNest(MathAtom const & a, int c)
879 //lyxerr << "LCursor::handleNest: " << c << endl;
881 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
884 pushLeft(*nextInset());
888 int LCursor::targetX() const
890 if (x_target() != -1)
899 void LCursor::setTargetX()
901 // For now this is good enough. A better solution would be to
902 // avoid this rebreak by setting cursorX only after drawing
903 bottom().text()->redoParagraph(bottom().pit());
911 bool LCursor::inMacroMode() const
915 MathUnknownInset const * p = prevAtom()->asUnknownInset();
916 return p && !p->final();
920 MathUnknownInset * LCursor::activeMacro()
922 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
926 void LCursor::pullArg()
931 MathArray ar = cell();
932 if (popLeft() && inMathed()) {
934 cell().insert(pos(), ar);
937 //formula()->mutateToText();
942 void LCursor::touch()
948 DocIterator::const_iterator it = begin();
949 DocIterator::const_iterator et = end();
950 for ( ; it != et; ++it)
956 void LCursor::normalize()
958 if (idx() > lastidx()) {
959 lyxerr << "this should not really happen - 1: "
960 << idx() << ' ' << nargs()
961 << " in: " << &inset() << endl;
965 if (pos() > lastpos()) {
966 lyxerr << "this should not really happen - 2: "
967 << pos() << ' ' << lastpos() << " in idx: " << idx()
969 WriteStream wi(lyxerr, false, true);
970 inset().asMathInset()->write(wi);
977 bool LCursor::goUpDown(bool up)
979 // Be warned: The 'logic' implemented in this function is highly
980 // fragile. A distance of one pixel or a '<' vs '<=' _really
981 // matters. So fiddle around with it only if you think you know
982 // what you are doing!
988 // check if we had something else in mind, if not, this is the future goal
989 if (x_target() == -1)
994 // try neigbouring script insets
998 MathScriptInset const * p = prevAtom()->asScriptInset();
999 if (p && p->has(up)) {
1001 push(*const_cast<MathScriptInset*>(p));
1002 idx() = p->idxOfScript(up);
1009 if (pos() != lastpos()) {
1010 MathScriptInset const * p = nextAtom()->asScriptInset();
1011 if (p && p->has(up)) {
1012 push(*const_cast<MathScriptInset*>(p));
1013 idx() = p->idxOfScript(up);
1020 // FIXME: Switch this on for more robust movement
1023 return bruteFind3(*this, xo, yo, up);
1026 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1031 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1032 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1036 // try to find an inset that knows better then we
1038 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1040 if (inset().idxUpDown(*this, up)) {
1041 //lyxerr << "idxUpDown triggered" << endl;
1042 // try to find best position within this inset
1044 setCursor(bruteFind2(*this, xo, yo));
1048 // no such inset found, just take something "above"
1050 //lyxerr << "updown: popleft failed (strange case)" << endl;
1051 int ylow = up ? 0 : yo + 1;
1052 int yhigh = up ? yo - 1 : bv().workHeight();
1053 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1056 // any improvement so far?
1057 //lyxerr << "updown: popLeft succeeded" << endl;
1061 if (up ? ynew < yo : ynew > yo)
1065 // we should not come here.
1066 BOOST_ASSERT(false);
1071 void LCursor::handleFont(string const & font)
1073 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1077 safe = lyx::cap::grabAndEraseSelection(*this);
1080 if (lastpos() != 0) {
1081 // something left in the cell
1083 // cursor in first position
1085 } else if (pos() == lastpos()) {
1086 // cursor in last position
1089 // cursor in between. split cell
1090 MathArray::iterator bt = cell().begin();
1091 MathAtom at = createMathInset(font);
1092 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1093 cell().erase(bt, bt + pos());
1098 // nothing left in the cell
1106 void LCursor::message(string const & msg) const
1108 bv().owner()->getLyXFunc().setMessage(msg);
1112 void LCursor::errorMessage(string const & msg) const
1114 bv().owner()->getLyXFunc().setErrorMessage(msg);
1118 string LCursor::selectionAsString(bool label) const
1124 Buffer const & buffer = *bv().buffer();
1125 ParagraphList const & pars = text()->paragraphs();
1127 // should be const ...
1128 pit_type startpit = selBegin().pit();
1129 pit_type endpit = selEnd().pit();
1130 size_t const startpos = selBegin().pos();
1131 size_t const endpos = selEnd().pos();
1133 if (startpit == endpit)
1134 return pars[startpit].asString(buffer, startpos, endpos, label);
1136 // First paragraph in selection
1137 string result = pars[startpit].
1138 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1140 // The paragraphs in between (if any)
1141 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1142 Paragraph const & par = pars[pit];
1143 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1146 // Last paragraph in selection
1147 result += pars[endpit].asString(buffer, 0, endpos, label);
1153 return lyx::cap::grabSelection(*this);
1159 string LCursor::currentState()
1162 std::ostringstream os;
1168 return text()->currentState(*this);
1174 string LCursor::getPossibleLabel()
1176 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1180 Encoding const * LCursor::getEncoding() const
1187 // go up until first non-0 text is hit
1188 // (innermost text is 0 in mathed)
1189 for (s = depth() - 1; s >= 0; --s)
1190 if (operator[](s).text())
1192 CursorSlice const & sl = operator[](s);
1193 LyXText const & text = *sl.text();
1194 LyXFont font = text.getPar(sl.pit()).getFont(
1195 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1196 return font.language()->encoding();
1200 void LCursor::undispatched()
1202 disp_.dispatched(false);
1206 void LCursor::dispatched()
1208 disp_.dispatched(true);
1212 void LCursor::needsUpdate()
1218 void LCursor::noUpdate()
1220 disp_.update(false);
1224 LyXFont LCursor::getFont() const
1226 // HACK. far from being perfect...
1228 // go up until first non-0 text is hit
1229 // (innermost text is 0 in mathed)
1230 for (s = depth() - 1; s >= 0; --s)
1231 if (operator[](s).text())
1233 CursorSlice const & sl = operator[](s);
1234 LyXText const & text = *sl.text();
1235 LyXFont font = text.getPar(sl.pit()).getFont(
1236 bv().buffer()->params(),
1238 outerFont(sl.pit(), text.paragraphs()));
1244 void LCursor::fixIfBroken()
1246 // find out last good level
1247 LCursor copy = *this;
1248 size_t newdepth = depth();
1249 while (!copy.empty()) {
1250 if (copy.idx() > copy.lastidx()) {
1251 lyxerr << "wrong idx " << copy.idx()
1252 << ", max is " << copy.lastidx()
1253 << " at level " << copy.depth()
1254 << ". Trying to correct this." << endl;
1255 newdepth = copy.depth() - 1;
1257 else if (copy.pit() > copy.lastpit()) {
1258 lyxerr << "wrong pit " << copy.pit()
1259 << ", max is " << copy.lastpit()
1260 << " at level " << copy.depth()
1261 << ". Trying to correct this." << endl;
1262 newdepth = copy.depth() - 1;
1264 else if (copy.pos() > copy.lastpos()) {
1265 lyxerr << "wrong pos " << copy.pos()
1266 << ", max is " << copy.lastpos()
1267 << " at level " << copy.depth()
1268 << ". Trying to correct this." << endl;
1269 newdepth = copy.depth() - 1;
1273 // shrink cursor to a size where everything is valid, possibly
1275 while (depth() > newdepth) {
1277 lyxerr << "correcting cursor to level " << depth() << endl;