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>
54 using lyx::CoordCache;
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().asInsetMath()->cell(et.top().idx()).size();
99 for (size_t i = 0; ; ++i) {
102 InsetBase const * inset = &it.inset();
103 Point o = c.bv().coordCache().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();
131 BufferView & bv = cursor.bv();
133 CoordCache::InnerParPosCache const & cache =
134 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
135 // Get an iterator on the first paragraph in the cache
136 DocIterator it(inset);
137 it.push_back(CursorSlice(inset));
138 it.pit() = cache.begin()->first;
139 // Get an iterator after the last paragraph in the cache
140 DocIterator et(inset);
141 et.push_back(CursorSlice(inset));
142 et.pit() = boost::prior(cache.end())->first;
143 if (et.pit() >= et.lastpit())
144 et = doc_iterator_end(inset);
148 double best_dist = std::numeric_limits<double>::max();;
149 DocIterator best_cursor = et;
151 for ( ; it != et; it.forwardPos(true)) {
152 // avoid invalid nesting when selecting
153 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
154 Point p = bv_funcs::getPos(bv, it, false);
157 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
158 double const dx = xo - x;
159 double const dy = yo - y;
160 double const d = dx * dx + dy * dy;
161 // '<=' in order to take the last possible position
162 // this is important for clicking behind \sum in e.g. '\sum_i a'
163 if (d <= best_dist) {
164 // lyxerr << "*" << endl;
172 if (best_cursor != et) {
173 cursor.setCursor(best_cursor);
181 /// moves position closest to (x, y) in given box
182 bool bruteFind3(LCursor & cur, int x, int y, bool up)
184 BufferView & bv = cur.bv();
185 int ylow = up ? 0 : y + 1;
186 int yhigh = up ? y - 1 : bv.workHeight();
188 int xhigh = bv.workWidth();
190 // FIXME: bit more work needed to get 'from' and 'to' right.
191 pit_type from = cur.bottom().pit();
192 //pit_type to = cur.bottom().pit();
193 //lyxerr << "Pit start: " << from << endl;
195 //lyxerr << "bruteFind3: x: " << x << " y: " << y
196 // << " xlow: " << xlow << " xhigh: " << xhigh
197 // << " ylow: " << ylow << " yhigh: " << yhigh
199 InsetBase & inset = bv.buffer()->inset();
200 DocIterator it = doc_iterator_begin(inset);
202 DocIterator et = doc_iterator_end(inset);
204 double best_dist = std::numeric_limits<double>::max();
205 DocIterator best_cursor = et;
207 for ( ; it != et; it.forwardPos()) {
208 // avoid invalid nesting when selecting
209 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
210 && (!cur.selection() || positionable(it, cur.anchor_))) {
211 Point p = bv_funcs::getPos(bv, it, false);
214 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
215 double const dx = xo - x;
216 double const dy = yo - y;
217 double const d = dx * dx + dy * dy;
218 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
219 // << " dx: " << dx << " dy: " << dy
220 // << " idx: " << it.idx() << " pos: " << it.pos()
223 // '<=' in order to take the last possible position
224 // this is important for clicking behind \sum in e.g. '\sum_i a'
225 if (d <= best_dist) {
226 //lyxerr << "*" << endl;
234 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
235 if (best_cursor == et)
237 cur.setCursor(best_cursor);
244 // be careful: this is called from the bv's constructor, too, so
245 // bv functions are not yet available!
246 LCursor::LCursor(BufferView & bv)
247 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
248 selection_(false), mark_(false), logicalpos_(false)
252 void LCursor::reset(InsetBase & inset)
255 push_back(CursorSlice(inset));
256 anchor_ = DocIterator(inset);
263 // this (intentionally) does neither touch anchor nor selection status
264 void LCursor::setCursor(DocIterator const & cur)
266 DocIterator::operator=(cur);
270 void LCursor::dispatch(FuncRequest const & cmd0)
272 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
273 << " cmd: " << cmd0 << '\n'
279 FuncRequest cmd = cmd0;
280 LCursor safe = *this;
282 for (; depth(); pop()) {
283 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
284 << cmd0 << endl << *this << endl;
285 BOOST_ASSERT(pos() <= lastpos());
286 BOOST_ASSERT(idx() <= lastidx());
287 BOOST_ASSERT(pit() <= lastpit());
289 // The common case is 'LFUN handled, need update', so make the
290 // LFUN handler's life easier by assuming this as default value.
291 // The handler can reset the update and val flags if necessary.
293 disp_.dispatched(true);
294 inset().dispatch(*this, cmd);
295 if (disp_.dispatched())
298 // it completely to get a 'bomb early' behaviour in case this
299 // object will be used again.
300 if (!disp_.dispatched()) {
301 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
303 disp_.dispatched(false);
308 DispatchResult LCursor::result() const
314 BufferView & LCursor::bv() const
321 Buffer & LCursor::buffer() const
324 BOOST_ASSERT(bv_->buffer());
325 return *bv_->buffer();
331 BOOST_ASSERT(depth() >= 1);
336 void LCursor::push(InsetBase & p)
338 push_back(CursorSlice(p));
342 void LCursor::pushLeft(InsetBase & p)
344 BOOST_ASSERT(!empty());
345 //lyxerr << "Entering inset " << t << " left" << endl;
351 bool LCursor::popLeft()
353 BOOST_ASSERT(!empty());
354 //lyxerr << "Leaving inset to the left" << endl;
355 inset().notifyCursorLeaves(*this);
363 bool LCursor::popRight()
365 BOOST_ASSERT(!empty());
366 //lyxerr << "Leaving inset to the right" << endl;
367 inset().notifyCursorLeaves(*this);
376 int LCursor::currentMode()
378 BOOST_ASSERT(!empty());
379 for (int i = depth() - 1; i >= 0; --i) {
380 int res = operator[](i).inset().currentMode();
381 if (res != InsetBase::UNDECIDED_MODE)
384 return InsetBase::TEXT_MODE;
388 void LCursor::getPos(int & x, int & y) const
390 Point p = bv_funcs::getPos(bv(), *this, boundary());
396 void LCursor::resetAnchor()
403 bool LCursor::posLeft()
412 bool LCursor::posRight()
414 if (pos() == lastpos())
421 CursorSlice LCursor::anchor() const
423 BOOST_ASSERT(anchor_.depth() >= depth());
424 CursorSlice normal = anchor_[depth() - 1];
425 if (depth() < anchor_.depth() && top() <= normal) {
426 // anchor is behind cursor -> move anchor behind the inset
433 CursorSlice LCursor::selBegin() const
437 return anchor() < top() ? anchor() : top();
441 CursorSlice LCursor::selEnd() const
445 return anchor() > top() ? anchor() : top();
449 DocIterator LCursor::selectionBegin() const
453 DocIterator di = (anchor() < top() ? anchor_ : *this);
459 DocIterator LCursor::selectionEnd() const
463 DocIterator di = (anchor() > top() ? anchor_ : *this);
464 if (di.depth() > depth()) {
472 void LCursor::setSelection()
475 // A selection with no contents is not a selection
477 #warning doesnt look ok
479 if (pit() == anchor().pit() && pos() == anchor().pos())
484 void LCursor::setSelection(DocIterator const & where, size_t n)
493 void LCursor::clearSelection()
501 int & LCursor::x_target()
507 int LCursor::x_target() const
513 void LCursor::clearTargetX()
520 void LCursor::info(std::ostream & os) const
522 for (int i = 1, n = depth(); i < n; ++i) {
523 operator[](i).inset().infoize(os);
527 prevInset()->infoize2(os);
528 // overwite old message
533 void LCursor::selHandle(bool sel)
535 //lyxerr << "LCursor::selHandle" << endl;
536 if (sel == selection())
544 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
546 os << "\n cursor: | anchor:\n";
547 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
548 os << " " << cur[i] << " | ";
549 if (i < cur.anchor_.depth())
550 os << cur.anchor_[i];
552 os << "-------------------------------";
555 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
556 os << "------------------------------- | " << cur.anchor_[i] << "\n";
558 os << " selection: " << cur.selection_
559 << " x_target: " << cur.x_target_ << endl;
566 ///////////////////////////////////////////////////////////////////
568 // The part below is the non-integrated rest of the original math
569 // cursor. This should be either generalized for texted or moved
570 // back to mathed (in most cases to InsetMathNest).
572 ///////////////////////////////////////////////////////////////////
574 #include "mathed/InsetMathChar.h"
575 #include "mathed/MathFactory.h"
576 #include "mathed/InsetMathGrid.h"
577 #include "mathed/MathMacroArgument.h"
578 #include "mathed/MathMLStream.h"
579 #include "mathed/InsetMathScript.h"
580 #include "mathed/MathSupport.h"
581 #include "mathed/InsetMathUnknown.h"
583 //#define FILEDEBUG 1
586 bool LCursor::isInside(InsetBase const * p)
588 for (size_t i = 0; i != depth(); ++i)
589 if (&operator[](i).inset() == p)
595 void LCursor::leaveInset(InsetBase const & inset)
597 for (size_t i = 0; i != depth(); ++i) {
598 if (&operator[](i).inset() == &inset) {
606 bool LCursor::openable(MathAtom const & t) const
617 // we can't move into anything new during selection
618 if (depth() >= anchor_.depth())
620 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
627 void LCursor::setScreenPos(int x, int y)
630 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
635 void LCursor::plainErase()
641 void LCursor::markInsert()
643 insert(char_type(0));
647 void LCursor::markErase()
653 void LCursor::plainInsert(MathAtom const & t)
655 cell().insert(pos(), t);
660 void LCursor::insert(string const & str)
662 for_each(str.begin(), str.end(),
663 boost::bind(static_cast<void(LCursor::*)(char_type)>
664 (&LCursor::insert), this, _1));
668 void LCursor::insert(char_type c)
670 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
671 BOOST_ASSERT(!empty());
673 lyx::cap::selClearOrDel(*this);
674 insert(new InsetMathChar(c));
676 text()->insertChar(*this, c);
681 void LCursor::insert(MathAtom const & t)
683 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
685 lyx::cap::selClearOrDel(*this);
690 void LCursor::insert(InsetBase * inset)
693 insert(MathAtom(inset));
695 text()->insertInset(*this, inset);
699 void LCursor::niceInsert(string const & t)
710 void LCursor::niceInsert(MathAtom const & t)
713 string const safe = lyx::cap::grabAndEraseSelection(*this);
715 // enter the new inset and move the contents of the selection if possible
718 // be careful here: don't use 'pushLeft(t)' as this we need to
719 // push the clone, not the original
720 pushLeft(*nextInset());
721 // We may not use niceInsert here (recursion)
729 void LCursor::insert(MathArray const & ar)
733 lyx::cap::eraseSelection(*this);
734 cell().insert(pos(), ar);
739 bool LCursor::backspace()
741 autocorrect() = false;
744 lyx::cap::selDel(*this);
749 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
756 InsetMathUnknown * p = activeMacro();
757 if (p->name().size() > 1) {
758 p->setName(p->name().substr(0, p->name().size() - 1));
763 if (pos() != 0 && prevAtom()->nargs() > 0) {
764 // let's require two backspaces for 'big stuff' and
765 // highlight on the first
777 bool LCursor::erase()
779 autocorrect() = false;
784 lyx::cap::selDel(*this);
788 // delete empty cells if possible
789 if (pos() == lastpos() && inset().idxDelete(idx()))
792 // special behaviour when in last position of cell
793 if (pos() == lastpos()) {
794 bool one_cell = inset().nargs() == 1;
795 if (one_cell && depth() == 1 && lastpos() == 0)
801 inset().idxGlue(idx());
805 // 'clever' UI hack: only erase large items if previously slected
806 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
821 DocIterator save = *this;
825 autocorrect() = false;
833 DocIterator save = *this;
837 autocorrect() = false;
842 bool LCursor::macroModeClose()
846 InsetMathUnknown * p = activeMacro();
848 string const s = p->name();
852 // do nothing if the macro name is empty
856 // prevent entering of recursive macros
857 // FIXME: this is only a weak attempt... only prevents immediate
859 string const name = s.substr(1);
860 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
861 if (macro && macro->getInsetName() == name)
862 lyxerr << "can't enter recursive macro" << endl;
864 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
865 if (in && in->interpret(*this, s))
867 plainInsert(createInsetMath(name));
872 string LCursor::macroName()
874 return inMacroMode() ? activeMacro()->name() : string();
878 void LCursor::handleNest(MathAtom const & a, int c)
880 //lyxerr << "LCursor::handleNest: " << c << endl;
882 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
885 pushLeft(*nextInset());
889 int LCursor::targetX() const
891 if (x_target() != -1)
900 void LCursor::setTargetX()
902 // For now this is good enough. A better solution would be to
903 // avoid this rebreak by setting cursorX only after drawing
904 bottom().text()->redoParagraph(bottom().pit());
912 bool LCursor::inMacroMode() const
916 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
917 return p && !p->final();
921 InsetMathUnknown * LCursor::activeMacro()
923 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
927 void LCursor::pullArg()
932 MathArray ar = cell();
933 if (popLeft() && inMathed()) {
935 cell().insert(pos(), ar);
938 //formula()->mutateToText();
943 void LCursor::touch()
949 DocIterator::const_iterator it = begin();
950 DocIterator::const_iterator et = end();
951 for ( ; it != et; ++it)
957 void LCursor::normalize()
959 if (idx() > lastidx()) {
960 lyxerr << "this should not really happen - 1: "
961 << idx() << ' ' << nargs()
962 << " in: " << &inset() << endl;
966 if (pos() > lastpos()) {
967 lyxerr << "this should not really happen - 2: "
968 << pos() << ' ' << lastpos() << " in idx: " << idx()
970 WriteStream wi(lyxerr, false, true);
971 inset().asInsetMath()->write(wi);
978 bool LCursor::goUpDown(bool up)
980 // Be warned: The 'logic' implemented in this function is highly
981 // fragile. A distance of one pixel or a '<' vs '<=' _really
982 // matters. So fiddle around with it only if you think you know
983 // what you are doing!
989 // check if we had something else in mind, if not, this is the future
991 if (x_target() == -1)
996 // try neigbouring script insets
1000 InsetMathScript const * p = prevAtom()->asScriptInset();
1001 if (p && p->has(up)) {
1003 push(*const_cast<InsetMathScript*>(p));
1004 idx() = p->idxOfScript(up);
1011 if (pos() != lastpos()) {
1012 InsetMathScript const * p = nextAtom()->asScriptInset();
1013 if (p && p->has(up)) {
1014 push(*const_cast<InsetMathScript*>(p));
1015 idx() = p->idxOfScript(up);
1022 // FIXME: Switch this on for more robust movement
1025 return bruteFind3(*this, xo, yo, up);
1028 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1033 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1034 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1038 // try to find an inset that knows better then we
1040 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1042 if (inset().idxUpDown(*this, up)) {
1043 //lyxerr << "idxUpDown triggered" << endl;
1044 // try to find best position within this inset
1046 setCursor(bruteFind2(*this, xo, yo));
1050 // no such inset found, just take something "above"
1052 //lyxerr << "updown: popleft failed (strange case)" << endl;
1053 int ylow = up ? 0 : yo + 1;
1054 int yhigh = up ? yo - 1 : bv().workHeight();
1055 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1058 // any improvement so far?
1059 //lyxerr << "updown: popLeft succeeded" << endl;
1063 if (up ? ynew < yo : ynew > yo)
1067 // we should not come here.
1068 BOOST_ASSERT(false);
1073 void LCursor::handleFont(string const & font)
1075 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1079 safe = lyx::cap::grabAndEraseSelection(*this);
1082 if (lastpos() != 0) {
1083 // something left in the cell
1085 // cursor in first position
1087 } else if (pos() == lastpos()) {
1088 // cursor in last position
1091 // cursor in between. split cell
1092 MathArray::iterator bt = cell().begin();
1093 MathAtom at = createInsetMath(font);
1094 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1095 cell().erase(bt, bt + pos());
1100 // nothing left in the cell
1108 void LCursor::message(docstring const & msg) const
1110 theLyXFunc().setMessage(msg);
1114 void LCursor::errorMessage(docstring const & msg) const
1116 theLyXFunc().setErrorMessage(msg);
1120 docstring LCursor::selectionAsString(bool label) const
1126 Buffer const & buffer = *bv().buffer();
1127 ParagraphList const & pars = text()->paragraphs();
1129 // should be const ...
1130 pit_type startpit = selBegin().pit();
1131 pit_type endpit = selEnd().pit();
1132 size_t const startpos = selBegin().pos();
1133 size_t const endpos = selEnd().pos();
1135 if (startpit == endpit)
1136 return pars[startpit].asString(buffer, startpos, endpos, label);
1138 // First paragraph in selection
1139 docstring result = pars[startpit].
1140 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1142 // The paragraphs in between (if any)
1143 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1144 Paragraph const & par = pars[pit];
1145 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1148 // Last paragraph in selection
1149 result += pars[endpit].asString(buffer, 0, endpos, label);
1155 return lyx::from_utf8(lyx::cap::grabSelection(*this));
1161 string LCursor::currentState()
1164 std::ostringstream os;
1170 return text()->currentState(*this);
1176 string LCursor::getPossibleLabel()
1178 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1182 Encoding const * LCursor::getEncoding() const
1189 // go up until first non-0 text is hit
1190 // (innermost text is 0 in mathed)
1191 for (s = depth() - 1; s >= 0; --s)
1192 if (operator[](s).text())
1194 CursorSlice const & sl = operator[](s);
1195 LyXText const & text = *sl.text();
1196 LyXFont font = text.getPar(sl.pit()).getFont(
1197 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1198 return font.language()->encoding();
1202 void LCursor::undispatched()
1204 disp_.dispatched(false);
1208 void LCursor::dispatched()
1210 disp_.dispatched(true);
1214 void LCursor::needsUpdate()
1220 void LCursor::noUpdate()
1222 disp_.update(false);
1226 LyXFont LCursor::getFont() const
1228 // HACK. far from being perfect...
1230 // go up until first non-0 text is hit
1231 // (innermost text is 0 in mathed)
1232 for (s = depth() - 1; s >= 0; --s)
1233 if (operator[](s).text())
1235 CursorSlice const & sl = operator[](s);
1236 LyXText const & text = *sl.text();
1237 LyXFont font = text.getPar(sl.pit()).getFont(
1238 bv().buffer()->params(),
1240 outerFont(sl.pit(), text.paragraphs()));
1246 void LCursor::fixIfBroken()
1248 // find out last good level
1249 LCursor copy = *this;
1250 size_t newdepth = depth();
1251 while (!copy.empty()) {
1252 if (copy.idx() > copy.lastidx()) {
1253 lyxerr << "wrong idx " << copy.idx()
1254 << ", max is " << copy.lastidx()
1255 << " at level " << copy.depth()
1256 << ". Trying to correct this." << endl;
1257 newdepth = copy.depth() - 1;
1259 else if (copy.pit() > copy.lastpit()) {
1260 lyxerr << "wrong pit " << copy.pit()
1261 << ", max is " << copy.lastpit()
1262 << " at level " << copy.depth()
1263 << ". Trying to correct this." << endl;
1264 newdepth = copy.depth() - 1;
1266 else if (copy.pos() > copy.lastpos()) {
1267 lyxerr << "wrong pos " << copy.pos()
1268 << ", max is " << copy.lastpos()
1269 << " at level " << copy.depth()
1270 << ". Trying to correct this." << endl;
1271 newdepth = copy.depth() - 1;
1275 // shrink cursor to a size where everything is valid, possibly
1277 while (depth() > newdepth) {
1279 lyxerr << "correcting cursor to level " << depth() << endl;