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 it.inset().cursorPos(it.top(), c.boundary() && ((i+1) == it.depth()), xo, yo);
101 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
102 // '<=' in order to take the last possible position
103 // this is important for clicking behind \sum in e.g. '\sum_i a'
104 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
105 << " best: " << best_dist << endl;
106 if (d <= best_dist) {
118 /// moves position closest to (x, y) in given box
119 bool bruteFind(LCursor & cursor,
120 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
122 BOOST_ASSERT(!cursor.empty());
123 InsetBase & inset = cursor[0].inset();
125 DocIterator it = doc_iterator_begin(inset);
126 DocIterator const et = doc_iterator_end(inset);
128 double best_dist = std::numeric_limits<double>::max();;
129 DocIterator best_cursor = et;
131 for ( ; it != et; it.forwardPos()) {
132 // avoid invalid nesting when selecting
133 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
134 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
135 Point p = bv_funcs::getPos(it, false);
138 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
139 double const dx = xo - x;
140 double const dy = yo - y;
141 double const d = dx * dx + dy * dy;
142 // '<=' in order to take the last possible position
143 // this is important for clicking behind \sum in e.g. '\sum_i a'
144 if (d <= best_dist) {
145 lyxerr << "*" << endl;
153 if (best_cursor != et) {
154 cursor.setCursor(best_cursor);
162 /// moves position closest to (x, y) in given box
163 bool bruteFind3(LCursor & cur, int x, int y, bool up)
165 BufferView & bv = cur.bv();
166 int ylow = up ? 0 : y + 1;
167 int yhigh = up ? y - 1 : bv.workHeight();
169 int xhigh = bv.workWidth();
171 // FIXME: bit more work needed to get 'from' and 'to' right.
172 pit_type from = cur.bottom().pit();
173 //pit_type to = cur.bottom().pit();
174 //lyxerr << "Pit start: " << from << endl;
176 //lyxerr << "bruteFind3: x: " << x << " y: " << y
177 // << " xlow: " << xlow << " xhigh: " << xhigh
178 // << " ylow: " << ylow << " yhigh: " << yhigh
180 InsetBase & inset = bv.buffer()->inset();
181 DocIterator it = doc_iterator_begin(inset);
183 DocIterator et = doc_iterator_end(inset);
185 double best_dist = std::numeric_limits<double>::max();
186 DocIterator best_cursor = et;
188 for ( ; it != et; it.forwardPos()) {
189 // avoid invalid nesting when selecting
190 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
191 && (!cur.selection() || positionable(it, cur.anchor_))) {
192 Point p = bv_funcs::getPos(it, false);
195 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
196 double const dx = xo - x;
197 double const dy = yo - y;
198 double const d = dx * dx + dy * dy;
199 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
200 // << " dx: " << dx << " dy: " << dy
201 // << " idx: " << it.idx() << " pos: " << it.pos()
204 // '<=' in order to take the last possible position
205 // this is important for clicking behind \sum in e.g. '\sum_i a'
206 if (d <= best_dist) {
207 //lyxerr << "*" << endl;
215 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
216 if (best_cursor == et)
218 cur.setCursor(best_cursor);
225 // be careful: this is called from the bv's constructor, too, so
226 // bv functions are not yet available!
227 LCursor::LCursor(BufferView & bv)
228 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
229 selection_(false), mark_(false), logicalpos_(false)
233 void LCursor::reset(InsetBase & inset)
236 push_back(CursorSlice(inset));
237 anchor_ = DocIterator(inset);
244 // this (intentionally) does neither touch anchor nor selection status
245 void LCursor::setCursor(DocIterator const & cur)
247 DocIterator::operator=(cur);
251 void LCursor::dispatch(FuncRequest const & cmd0)
253 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
254 << " cmd: " << cmd0 << '\n'
260 FuncRequest cmd = cmd0;
261 LCursor safe = *this;
263 for (; depth(); pop()) {
264 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
265 << cmd0 << endl << *this << endl;
266 BOOST_ASSERT(pos() <= lastpos());
267 BOOST_ASSERT(idx() <= lastidx());
268 BOOST_ASSERT(pit() <= lastpit());
270 // The common case is 'LFUN handled, need update', so make the
271 // LFUN handler's life easier by assuming this as default value.
272 // The handler can reset the update and val flags if necessary.
274 disp_.dispatched(true);
275 inset().dispatch(*this, cmd);
276 if (disp_.dispatched())
279 // it completely to get a 'bomb early' behaviour in case this
280 // object will be used again.
281 if (!disp_.dispatched()) {
282 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
284 disp_.dispatched(false);
289 DispatchResult LCursor::result() const
295 BufferView & LCursor::bv() const
302 Buffer & LCursor::buffer() const
305 BOOST_ASSERT(bv_->buffer());
306 return *bv_->buffer();
312 BOOST_ASSERT(depth() >= 1);
317 void LCursor::push(InsetBase & p)
319 push_back(CursorSlice(p));
323 void LCursor::pushLeft(InsetBase & p)
325 BOOST_ASSERT(!empty());
326 //lyxerr << "Entering inset " << t << " left" << endl;
332 bool LCursor::popLeft()
334 BOOST_ASSERT(!empty());
335 //lyxerr << "Leaving inset to the left" << endl;
336 inset().notifyCursorLeaves(*this);
344 bool LCursor::popRight()
346 BOOST_ASSERT(!empty());
347 //lyxerr << "Leaving inset to the right" << endl;
348 inset().notifyCursorLeaves(*this);
357 int LCursor::currentMode()
359 BOOST_ASSERT(!empty());
360 for (int i = depth() - 1; i >= 0; --i) {
361 int res = operator[](i).inset().currentMode();
362 if (res != InsetBase::UNDECIDED_MODE)
365 return InsetBase::TEXT_MODE;
369 void LCursor::getPos(int & x, int & y) const
371 Point p = bv_funcs::getPos(*this, boundary());
377 void LCursor::paste(string const & data)
380 dispatch(FuncRequest(LFUN_PASTE, data));
384 void LCursor::resetAnchor()
391 bool LCursor::posLeft()
400 bool LCursor::posRight()
402 if (pos() == lastpos())
409 CursorSlice LCursor::anchor() const
411 BOOST_ASSERT(anchor_.depth() >= depth());
412 CursorSlice normal = anchor_[depth() - 1];
413 if (depth() < anchor_.depth() && top() <= normal) {
414 // anchor is behind cursor -> move anchor behind the inset
421 CursorSlice LCursor::selBegin() const
425 return anchor() < top() ? anchor() : top();
429 CursorSlice LCursor::selEnd() const
433 return anchor() > top() ? anchor() : top();
437 DocIterator LCursor::selectionBegin() const
441 DocIterator di = (anchor() < top() ? anchor_ : *this);
447 DocIterator LCursor::selectionEnd() const
451 DocIterator di = (anchor() > top() ? anchor_ : *this);
452 if (di.depth() > depth()) {
460 void LCursor::setSelection()
463 // A selection with no contents is not a selection
465 #warning doesnt look ok
467 if (pit() == anchor().pit() && pos() == anchor().pos())
472 void LCursor::setSelection(DocIterator const & where, size_t n)
481 void LCursor::clearSelection()
490 int & LCursor::x_target()
496 int LCursor::x_target() const
502 void LCursor::clearTargetX()
509 void LCursor::info(std::ostream & os) const
511 for (int i = 1, n = depth(); i < n; ++i) {
512 operator[](i).inset().infoize(os);
516 prevInset()->infoize2(os);
517 // overwite old message
522 void LCursor::selHandle(bool sel)
524 //lyxerr << "LCursor::selHandle" << endl;
525 if (sel == selection())
533 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
535 os << "\n cursor: | anchor:\n";
536 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
537 os << " " << cur[i] << " | ";
538 if (i < cur.anchor_.depth())
539 os << cur.anchor_[i];
541 os << "-------------------------------";
544 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
545 os << "------------------------------- | " << cur.anchor_[i] << "\n";
547 os << " selection: " << cur.selection_
548 << " x_target: " << cur.x_target_ << endl;
555 ///////////////////////////////////////////////////////////////////
557 // The part below is the non-integrated rest of the original math
558 // cursor. This should be either generalized for texted or moved
559 // back to mathed (in most cases to MathNestInset).
561 ///////////////////////////////////////////////////////////////////
563 #include "mathed/math_charinset.h"
564 #include "mathed/math_factory.h"
565 #include "mathed/math_gridinset.h"
566 #include "mathed/math_macroarg.h"
567 #include "mathed/math_mathmlstream.h"
568 #include "mathed/math_scriptinset.h"
569 #include "mathed/math_support.h"
570 #include "mathed/math_unknowninset.h"
572 //#define FILEDEBUG 1
575 bool LCursor::isInside(InsetBase const * p)
577 for (size_t i = 0; i != depth(); ++i)
578 if (&operator[](i).inset() == p)
584 void LCursor::leaveInset(InsetBase const & inset)
586 for (size_t i = 0; i != depth(); ++i) {
587 if (&operator[](i).inset() == &inset) {
595 bool LCursor::openable(MathAtom const & t) const
606 // we can't move into anything new during selection
607 if (depth() >= anchor_.depth())
609 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
616 void LCursor::setScreenPos(int x, int y)
619 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
624 void LCursor::plainErase()
630 void LCursor::markInsert()
636 void LCursor::markErase()
642 void LCursor::plainInsert(MathAtom const & t)
644 cell().insert(pos(), t);
649 void LCursor::insert(string const & str)
651 for_each(str.begin(), str.end(),
652 boost::bind(static_cast<void(LCursor::*)(char)>
653 (&LCursor::insert), this, _1));
657 void LCursor::insert(char c)
659 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
660 BOOST_ASSERT(!empty());
662 lyx::cap::selClearOrDel(*this);
663 insert(new MathCharInset(c));
665 text()->insertChar(*this, c);
670 void LCursor::insert(MathAtom const & t)
672 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
674 lyx::cap::selClearOrDel(*this);
679 void LCursor::insert(InsetBase * inset)
682 insert(MathAtom(inset));
684 text()->insertInset(*this, inset);
688 void LCursor::niceInsert(string const & t)
699 void LCursor::niceInsert(MathAtom const & t)
702 string const safe = lyx::cap::grabAndEraseSelection(*this);
704 // enter the new inset and move the contents of the selection if possible
707 // be careful here: don't use 'pushLeft(t)' as this we need to
708 // push the clone, not the original
709 pushLeft(*nextInset());
715 void LCursor::insert(MathArray const & ar)
719 lyx::cap::eraseSelection(*this);
720 cell().insert(pos(), ar);
725 bool LCursor::backspace()
727 autocorrect() = false;
730 lyx::cap::selDel(*this);
735 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
742 MathUnknownInset * p = activeMacro();
743 if (p->name().size() > 1) {
744 p->setName(p->name().substr(0, p->name().size() - 1));
749 if (pos() != 0 && prevAtom()->nargs() > 0) {
750 // let's require two backspaces for 'big stuff' and
751 // highlight on the first
763 bool LCursor::erase()
765 autocorrect() = false;
770 lyx::cap::selDel(*this);
774 // delete empty cells if possible
775 if (pos() == lastpos() && inset().idxDelete(idx()))
778 // special behaviour when in last position of cell
779 if (pos() == lastpos()) {
780 bool one_cell = inset().nargs() == 1;
781 if (one_cell && depth() == 1 && lastpos() == 0)
787 inset().idxGlue(idx());
791 // 'clever' UI hack: only erase large items if previously slected
792 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
807 DocIterator save = *this;
811 autocorrect() = false;
819 DocIterator save = *this;
823 autocorrect() = false;
828 bool LCursor::macroModeClose()
832 MathUnknownInset * p = activeMacro();
834 string const s = p->name();
838 // do nothing if the macro name is empty
842 // prevent entering of recursive macros
843 // FIXME: this is only a weak attempt... only prevents immediate
845 string const name = s.substr(1);
846 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
847 if (macro && macro->getInsetName() == name)
848 lyxerr << "can't enter recursive macro" << endl;
850 plainInsert(createMathInset(name));
855 string LCursor::macroName()
857 return inMacroMode() ? activeMacro()->name() : string();
861 void LCursor::handleNest(MathAtom const & a, int c)
863 //lyxerr << "LCursor::handleNest: " << c << endl;
865 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
868 pushLeft(*nextInset());
872 int LCursor::targetX() const
874 if (x_target() != -1)
883 void LCursor::setTargetX()
885 // For now this is good enough. A better solution would be to
886 // avoid this rebreak by setting cursorX only after drawing
887 bottom().text()->redoParagraph(bottom().pit());
895 bool LCursor::inMacroMode() const
899 MathUnknownInset const * p = prevAtom()->asUnknownInset();
900 return p && !p->final();
904 MathUnknownInset * LCursor::activeMacro()
906 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
910 void LCursor::pullArg()
915 MathArray ar = cell();
916 if (popLeft() && inMathed()) {
918 cell().insert(pos(), ar);
921 //formula()->mutateToText();
926 void LCursor::touch()
932 DocIterator::const_iterator it = begin();
933 DocIterator::const_iterator et = end();
934 for ( ; it != et; ++it)
940 void LCursor::normalize()
942 if (idx() > lastidx()) {
943 lyxerr << "this should not really happen - 1: "
944 << idx() << ' ' << nargs()
945 << " in: " << &inset() << endl;
949 if (pos() > lastpos()) {
950 lyxerr << "this should not really happen - 2: "
951 << pos() << ' ' << lastpos() << " in idx: " << idx()
953 WriteStream wi(lyxerr, false, true);
954 inset().asMathInset()->write(wi);
961 bool LCursor::goUpDown(bool up)
963 // Be warned: The 'logic' implemented in this function is highly
964 // fragile. A distance of one pixel or a '<' vs '<=' _really
965 // matters. So fiddle around with it only if you think you know
966 // what you are doing!
972 // check if we had something else in mind, if not, this is the future goal
973 if (x_target() == -1)
978 // try neigbouring script insets
982 MathScriptInset const * p = prevAtom()->asScriptInset();
983 if (p && p->has(up)) {
985 push(*const_cast<MathScriptInset*>(p));
986 idx() = p->idxOfScript(up);
993 if (pos() != lastpos()) {
994 MathScriptInset const * p = nextAtom()->asScriptInset();
995 if (p && p->has(up)) {
996 push(*const_cast<MathScriptInset*>(p));
997 idx() = p->idxOfScript(up);
1004 // FIXME: Switch this on for more robust movement
1007 return bruteFind3(*this, xo, yo, up);
1010 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1015 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1016 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1020 // try to find an inset that knows better then we
1022 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1024 if (inset().idxUpDown(*this, up)) {
1025 //lyxerr << "idxUpDown triggered" << endl;
1026 // try to find best position within this inset
1028 setCursor(bruteFind2(*this, xo, yo));
1032 // no such inset found, just take something "above"
1034 //lyxerr << "updown: popleft failed (strange case)" << endl;
1035 int ylow = up ? 0 : yo + 1;
1036 int yhigh = up ? yo - 1 : bv().workHeight();
1037 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1040 // any improvement so far?
1041 //lyxerr << "updown: popLeft succeeded" << endl;
1045 if (up ? ynew < yo : ynew > yo)
1049 // we should not come here.
1050 BOOST_ASSERT(false);
1055 void LCursor::handleFont(string const & font)
1057 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1061 safe = lyx::cap::grabAndEraseSelection(*this);
1064 if (lastpos() != 0) {
1065 // something left in the cell
1067 // cursor in first position
1069 } else if (pos() == lastpos()) {
1070 // cursor in last position
1073 // cursor in between. split cell
1074 MathArray::iterator bt = cell().begin();
1075 MathAtom at = createMathInset(font);
1076 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1077 cell().erase(bt, bt + pos());
1082 // nothing left in the cell
1090 void LCursor::message(string const & msg) const
1092 bv().owner()->getLyXFunc().setMessage(msg);
1096 void LCursor::errorMessage(string const & msg) const
1098 bv().owner()->getLyXFunc().setErrorMessage(msg);
1102 string LCursor::selectionAsString(bool label) const
1108 Buffer const & buffer = *bv().buffer();
1109 ParagraphList const & pars = text()->paragraphs();
1111 // should be const ...
1112 pit_type startpit = selBegin().pit();
1113 pit_type endpit = selEnd().pit();
1114 size_t const startpos = selBegin().pos();
1115 size_t const endpos = selEnd().pos();
1117 if (startpit == endpit)
1118 return pars[startpit].asString(buffer, startpos, endpos, label);
1120 // First paragraph in selection
1121 string result = pars[startpit].
1122 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1124 // The paragraphs in between (if any)
1125 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1126 Paragraph const & par = pars[pit];
1127 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1130 // Last paragraph in selection
1131 result += pars[endpit].asString(buffer, 0, endpos, label);
1137 return lyx::cap::grabSelection(*this);
1143 string LCursor::currentState()
1146 std::ostringstream os;
1152 return text()->currentState(*this);
1158 string LCursor::getPossibleLabel()
1160 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1164 Encoding const * LCursor::getEncoding() const
1171 // go up until first non-0 text is hit
1172 // (innermost text is 0 in mathed)
1173 for (s = depth() - 1; s >= 0; --s)
1174 if (operator[](s).text())
1176 CursorSlice const & sl = operator[](s);
1177 LyXText const & text = *sl.text();
1178 LyXFont font = text.getPar(sl.pit()).getFont(
1179 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1180 return font.language()->encoding();
1184 void LCursor::undispatched()
1186 disp_.dispatched(false);
1190 void LCursor::dispatched()
1192 disp_.dispatched(true);
1196 void LCursor::needsUpdate()
1202 void LCursor::noUpdate()
1204 disp_.update(false);
1208 LyXFont LCursor::getFont() const
1210 // HACK. far from being perfect...
1212 // go up until first non-0 text is hit
1213 // (innermost text is 0 in mathed)
1214 for (s = depth() - 1; s >= 0; --s)
1215 if (operator[](s).text())
1217 CursorSlice const & sl = operator[](s);
1218 LyXText const & text = *sl.text();
1219 LyXFont font = text.getPar(sl.pit()).getFont(
1220 bv().buffer()->params(),
1222 outerFont(sl.pit(), text.paragraphs()));
1228 void LCursor::fixIfBroken()
1230 // find out last good level
1231 LCursor copy = *this;
1232 size_t newdepth = depth();
1233 while (!copy.empty()) {
1234 if (copy.idx() > copy.lastidx()) {
1235 lyxerr << "wrong idx " << copy.idx()
1236 << ", max is " << copy.lastidx()
1237 << " at level " << copy.depth()
1238 << ". Trying to correct this." << endl;
1239 newdepth = copy.depth() - 1;
1241 else if (copy.pit() > copy.lastpit()) {
1242 lyxerr << "wrong pit " << copy.pit()
1243 << ", max is " << copy.lastpit()
1244 << " at level " << copy.depth()
1245 << ". Trying to correct this." << endl;
1246 newdepth = copy.depth() - 1;
1248 else if (copy.pos() > copy.lastpos()) {
1249 lyxerr << "wrong pos " << copy.pos()
1250 << ", max is " << copy.lastpos()
1251 << " at level " << copy.depth()
1252 << ". Trying to correct this." << endl;
1253 newdepth = copy.depth() - 1;
1257 // shrink cursor to a size where everything is valid, possibly
1259 while (depth() > newdepth) {
1261 lyxerr << "correcting cursor to level " << depth() << endl;