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>
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().asInsetMath()->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 CoordCache::InnerParPosCache const & cache = theCoords.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(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(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.
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_.dispatched(false);
304 DispatchResult LCursor::result() const
310 BufferView & LCursor::bv() const
317 Buffer & LCursor::buffer() const
320 BOOST_ASSERT(bv_->buffer());
321 return *bv_->buffer();
327 BOOST_ASSERT(depth() >= 1);
332 void LCursor::push(InsetBase & p)
334 push_back(CursorSlice(p));
338 void LCursor::pushLeft(InsetBase & p)
340 BOOST_ASSERT(!empty());
341 //lyxerr << "Entering inset " << t << " left" << endl;
347 bool LCursor::popLeft()
349 BOOST_ASSERT(!empty());
350 //lyxerr << "Leaving inset to the left" << endl;
351 inset().notifyCursorLeaves(*this);
359 bool LCursor::popRight()
361 BOOST_ASSERT(!empty());
362 //lyxerr << "Leaving inset to the right" << endl;
363 inset().notifyCursorLeaves(*this);
372 int LCursor::currentMode()
374 BOOST_ASSERT(!empty());
375 for (int i = depth() - 1; i >= 0; --i) {
376 int res = operator[](i).inset().currentMode();
377 if (res != InsetBase::UNDECIDED_MODE)
380 return InsetBase::TEXT_MODE;
384 void LCursor::getPos(int & x, int & y) const
386 Point p = bv_funcs::getPos(*this, boundary());
392 void LCursor::resetAnchor()
399 bool LCursor::posLeft()
408 bool LCursor::posRight()
410 if (pos() == lastpos())
417 CursorSlice LCursor::anchor() const
419 BOOST_ASSERT(anchor_.depth() >= depth());
420 CursorSlice normal = anchor_[depth() - 1];
421 if (depth() < anchor_.depth() && top() <= normal) {
422 // anchor is behind cursor -> move anchor behind the inset
429 CursorSlice LCursor::selBegin() const
433 return anchor() < top() ? anchor() : top();
437 CursorSlice LCursor::selEnd() const
441 return anchor() > top() ? anchor() : top();
445 DocIterator LCursor::selectionBegin() const
449 DocIterator di = (anchor() < top() ? anchor_ : *this);
455 DocIterator LCursor::selectionEnd() const
459 DocIterator di = (anchor() > top() ? anchor_ : *this);
460 if (di.depth() > depth()) {
468 void LCursor::setSelection()
471 // A selection with no contents is not a selection
473 #warning doesnt look ok
475 if (pit() == anchor().pit() && pos() == anchor().pos())
480 void LCursor::setSelection(DocIterator const & where, size_t n)
489 void LCursor::clearSelection()
497 int & LCursor::x_target()
503 int LCursor::x_target() const
509 void LCursor::clearTargetX()
516 void LCursor::info(std::ostream & os) const
518 for (int i = 1, n = depth(); i < n; ++i) {
519 operator[](i).inset().infoize(os);
523 prevInset()->infoize2(os);
524 // overwite old message
529 void LCursor::selHandle(bool sel)
531 //lyxerr << "LCursor::selHandle" << endl;
532 if (sel == selection())
540 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
542 os << "\n cursor: | anchor:\n";
543 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
544 os << " " << cur[i] << " | ";
545 if (i < cur.anchor_.depth())
546 os << cur.anchor_[i];
548 os << "-------------------------------";
551 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
552 os << "------------------------------- | " << cur.anchor_[i] << "\n";
554 os << " selection: " << cur.selection_
555 << " x_target: " << cur.x_target_ << endl;
562 ///////////////////////////////////////////////////////////////////
564 // The part below is the non-integrated rest of the original math
565 // cursor. This should be either generalized for texted or moved
566 // back to mathed (in most cases to InsetMathNest).
568 ///////////////////////////////////////////////////////////////////
570 #include "mathed/InsetMathChar.h"
571 #include "mathed/MathFactory.h"
572 #include "mathed/InsetMathGrid.h"
573 #include "mathed/MathMacroArgument.h"
574 #include "mathed/MathMLStream.h"
575 #include "mathed/InsetMathScript.h"
576 #include "mathed/MathSupport.h"
577 #include "mathed/InsetMathUnknown.h"
579 //#define FILEDEBUG 1
582 bool LCursor::isInside(InsetBase const * p)
584 for (size_t i = 0; i != depth(); ++i)
585 if (&operator[](i).inset() == p)
591 void LCursor::leaveInset(InsetBase const & inset)
593 for (size_t i = 0; i != depth(); ++i) {
594 if (&operator[](i).inset() == &inset) {
602 bool LCursor::openable(MathAtom const & t) const
613 // we can't move into anything new during selection
614 if (depth() >= anchor_.depth())
616 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
623 void LCursor::setScreenPos(int x, int y)
626 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
631 void LCursor::plainErase()
637 void LCursor::markInsert()
639 insert(char_type(0));
643 void LCursor::markErase()
649 void LCursor::plainInsert(MathAtom const & t)
651 cell().insert(pos(), t);
656 void LCursor::insert(string const & str)
658 for_each(str.begin(), str.end(),
659 boost::bind(static_cast<void(LCursor::*)(char_type)>
660 (&LCursor::insert), this, _1));
664 void LCursor::insert(char_type c)
666 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
667 BOOST_ASSERT(!empty());
669 lyx::cap::selClearOrDel(*this);
670 insert(new InsetMathChar(c));
672 text()->insertChar(*this, c);
677 void LCursor::insert(MathAtom const & t)
679 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
681 lyx::cap::selClearOrDel(*this);
686 void LCursor::insert(InsetBase * inset)
689 insert(MathAtom(inset));
691 text()->insertInset(*this, inset);
695 void LCursor::niceInsert(string const & t)
706 void LCursor::niceInsert(MathAtom const & t)
709 string const safe = lyx::cap::grabAndEraseSelection(*this);
711 // enter the new inset and move the contents of the selection if possible
714 // be careful here: don't use 'pushLeft(t)' as this we need to
715 // push the clone, not the original
716 pushLeft(*nextInset());
717 // We may not use niceInsert here (recursion)
725 void LCursor::insert(MathArray const & ar)
729 lyx::cap::eraseSelection(*this);
730 cell().insert(pos(), ar);
735 bool LCursor::backspace()
737 autocorrect() = false;
740 lyx::cap::selDel(*this);
745 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
752 InsetMathUnknown * p = activeMacro();
753 if (p->name().size() > 1) {
754 p->setName(p->name().substr(0, p->name().size() - 1));
759 if (pos() != 0 && prevAtom()->nargs() > 0) {
760 // let's require two backspaces for 'big stuff' and
761 // highlight on the first
773 bool LCursor::erase()
775 autocorrect() = false;
780 lyx::cap::selDel(*this);
784 // delete empty cells if possible
785 if (pos() == lastpos() && inset().idxDelete(idx()))
788 // special behaviour when in last position of cell
789 if (pos() == lastpos()) {
790 bool one_cell = inset().nargs() == 1;
791 if (one_cell && depth() == 1 && lastpos() == 0)
797 inset().idxGlue(idx());
801 // 'clever' UI hack: only erase large items if previously slected
802 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
817 DocIterator save = *this;
821 autocorrect() = false;
829 DocIterator save = *this;
833 autocorrect() = false;
838 bool LCursor::macroModeClose()
842 InsetMathUnknown * p = activeMacro();
844 string const s = p->name();
848 // do nothing if the macro name is empty
852 // prevent entering of recursive macros
853 // FIXME: this is only a weak attempt... only prevents immediate
855 string const name = s.substr(1);
856 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
857 if (macro && macro->getInsetName() == name)
858 lyxerr << "can't enter recursive macro" << endl;
860 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
861 if (in && in->interpret(*this, s))
863 plainInsert(createInsetMath(name));
868 string LCursor::macroName()
870 return inMacroMode() ? activeMacro()->name() : string();
874 void LCursor::handleNest(MathAtom const & a, int c)
876 //lyxerr << "LCursor::handleNest: " << c << endl;
878 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
881 pushLeft(*nextInset());
885 int LCursor::targetX() const
887 if (x_target() != -1)
896 void LCursor::setTargetX()
898 // For now this is good enough. A better solution would be to
899 // avoid this rebreak by setting cursorX only after drawing
900 bottom().text()->redoParagraph(bottom().pit());
908 bool LCursor::inMacroMode() const
912 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
913 return p && !p->final();
917 InsetMathUnknown * LCursor::activeMacro()
919 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
923 void LCursor::pullArg()
928 MathArray ar = cell();
929 if (popLeft() && inMathed()) {
931 cell().insert(pos(), ar);
934 //formula()->mutateToText();
939 void LCursor::touch()
945 DocIterator::const_iterator it = begin();
946 DocIterator::const_iterator et = end();
947 for ( ; it != et; ++it)
953 void LCursor::normalize()
955 if (idx() > lastidx()) {
956 lyxerr << "this should not really happen - 1: "
957 << idx() << ' ' << nargs()
958 << " in: " << &inset() << endl;
962 if (pos() > lastpos()) {
963 lyxerr << "this should not really happen - 2: "
964 << pos() << ' ' << lastpos() << " in idx: " << idx()
966 WriteStream wi(lyxerr, false, true);
967 inset().asInsetMath()->write(wi);
974 bool LCursor::goUpDown(bool up)
976 // Be warned: The 'logic' implemented in this function is highly
977 // fragile. A distance of one pixel or a '<' vs '<=' _really
978 // matters. So fiddle around with it only if you think you know
979 // what you are doing!
985 // check if we had something else in mind, if not, this is the future
987 if (x_target() == -1)
992 // try neigbouring script insets
996 InsetMathScript const * p = prevAtom()->asScriptInset();
997 if (p && p->has(up)) {
999 push(*const_cast<InsetMathScript*>(p));
1000 idx() = p->idxOfScript(up);
1007 if (pos() != lastpos()) {
1008 InsetMathScript const * p = nextAtom()->asScriptInset();
1009 if (p && p->has(up)) {
1010 push(*const_cast<InsetMathScript*>(p));
1011 idx() = p->idxOfScript(up);
1018 // FIXME: Switch this on for more robust movement
1021 return bruteFind3(*this, xo, yo, up);
1024 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1029 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1030 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1034 // try to find an inset that knows better then we
1036 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1038 if (inset().idxUpDown(*this, up)) {
1039 //lyxerr << "idxUpDown triggered" << endl;
1040 // try to find best position within this inset
1042 setCursor(bruteFind2(*this, xo, yo));
1046 // no such inset found, just take something "above"
1048 //lyxerr << "updown: popleft failed (strange case)" << endl;
1049 int ylow = up ? 0 : yo + 1;
1050 int yhigh = up ? yo - 1 : bv().workHeight();
1051 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1054 // any improvement so far?
1055 //lyxerr << "updown: popLeft succeeded" << endl;
1059 if (up ? ynew < yo : ynew > yo)
1063 // we should not come here.
1064 BOOST_ASSERT(false);
1069 void LCursor::handleFont(string const & font)
1071 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1075 safe = lyx::cap::grabAndEraseSelection(*this);
1078 if (lastpos() != 0) {
1079 // something left in the cell
1081 // cursor in first position
1083 } else if (pos() == lastpos()) {
1084 // cursor in last position
1087 // cursor in between. split cell
1088 MathArray::iterator bt = cell().begin();
1089 MathAtom at = createInsetMath(font);
1090 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1091 cell().erase(bt, bt + pos());
1096 // nothing left in the cell
1104 void LCursor::message(docstring const & msg) const
1106 theLyXFunc().setMessage(msg);
1110 void LCursor::errorMessage(docstring const & msg) const
1112 theLyXFunc().setErrorMessage(msg);
1116 docstring LCursor::selectionAsString(bool label) const
1122 Buffer const & buffer = *bv().buffer();
1123 ParagraphList const & pars = text()->paragraphs();
1125 // should be const ...
1126 pit_type startpit = selBegin().pit();
1127 pit_type endpit = selEnd().pit();
1128 size_t const startpos = selBegin().pos();
1129 size_t const endpos = selEnd().pos();
1131 if (startpit == endpit)
1132 return pars[startpit].asString(buffer, startpos, endpos, label);
1134 // First paragraph in selection
1135 docstring result = pars[startpit].
1136 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1138 // The paragraphs in between (if any)
1139 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1140 Paragraph const & par = pars[pit];
1141 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1144 // Last paragraph in selection
1145 result += pars[endpit].asString(buffer, 0, endpos, label);
1151 return lyx::from_utf8(lyx::cap::grabSelection(*this));
1157 string LCursor::currentState()
1160 std::ostringstream os;
1166 return text()->currentState(*this);
1172 string LCursor::getPossibleLabel()
1174 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1178 Encoding const * LCursor::getEncoding() const
1185 // go up until first non-0 text is hit
1186 // (innermost text is 0 in mathed)
1187 for (s = depth() - 1; s >= 0; --s)
1188 if (operator[](s).text())
1190 CursorSlice const & sl = operator[](s);
1191 LyXText const & text = *sl.text();
1192 LyXFont font = text.getPar(sl.pit()).getFont(
1193 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1194 return font.language()->encoding();
1198 void LCursor::undispatched()
1200 disp_.dispatched(false);
1204 void LCursor::dispatched()
1206 disp_.dispatched(true);
1210 void LCursor::needsUpdate()
1216 void LCursor::noUpdate()
1218 disp_.update(false);
1222 LyXFont LCursor::getFont() const
1224 // HACK. far from being perfect...
1226 // go up until first non-0 text is hit
1227 // (innermost text is 0 in mathed)
1228 for (s = depth() - 1; s >= 0; --s)
1229 if (operator[](s).text())
1231 CursorSlice const & sl = operator[](s);
1232 LyXText const & text = *sl.text();
1233 LyXFont font = text.getPar(sl.pit()).getFont(
1234 bv().buffer()->params(),
1236 outerFont(sl.pit(), text.paragraphs()));
1242 void LCursor::fixIfBroken()
1244 // find out last good level
1245 LCursor copy = *this;
1246 size_t newdepth = depth();
1247 while (!copy.empty()) {
1248 if (copy.idx() > copy.lastidx()) {
1249 lyxerr << "wrong idx " << copy.idx()
1250 << ", max is " << copy.lastidx()
1251 << " at level " << copy.depth()
1252 << ". Trying to correct this." << endl;
1253 newdepth = copy.depth() - 1;
1255 else if (copy.pit() > copy.lastpit()) {
1256 lyxerr << "wrong pit " << copy.pit()
1257 << ", max is " << copy.lastpit()
1258 << " at level " << copy.depth()
1259 << ". Trying to correct this." << endl;
1260 newdepth = copy.depth() - 1;
1262 else if (copy.pos() > copy.lastpos()) {
1263 lyxerr << "wrong pos " << copy.pos()
1264 << ", max is " << copy.lastpos()
1265 << " at level " << copy.depth()
1266 << ". Trying to correct this." << endl;
1267 newdepth = copy.depth() - 1;
1271 // shrink cursor to a size where everything is valid, possibly
1273 while (depth() > newdepth) {
1275 lyxerr << "correcting cursor to level " << depth() << endl;