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 "CutAndPaste.h"
20 #include "dispatchresult.h"
22 #include "funcrequest.h"
26 #include "lyxfunc.h" // only for setMessage()
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "pariterator.h"
34 #include "insets/updatableinset.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_macrotable.h"
42 #include "support/limited_stack.h"
44 #include "frontends/LyXView.h"
46 #include <boost/assert.hpp>
47 #include <boost/current_function.hpp>
56 #ifndef CXX_GLOBAL_CSTD
65 (DocIterator const & cursor, DocIterator const & anchor)
67 // avoid deeper nested insets when selecting
68 if (cursor.size() > anchor.size())
71 // anchor might be deeper, should have same path then
72 for (size_t i = 0; i < cursor.size(); ++i)
73 if (&cursor[i].inset() != &anchor[i].inset())
76 // position should be ok.
81 // Find position closest to (x, y) in cell given by iter.
82 DocIterator bruteFind2(LCursor const & c, int x, int y)
84 double best_dist = 1e10;
91 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
92 for (int i = 0; ; ++i) {
96 cur.inset().getCursorPos(cur, xo, yo);
97 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
98 // '<=' in order to take the last possible position
99 // this is important for clicking behind \sum in e.g. '\sum_i a'
100 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d << " best: " << best_dist << endl;
101 if (d <= best_dist) {
113 /// moves position closest to (x, y) in given box
114 bool bruteFind(LCursor & cursor,
115 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
117 BOOST_ASSERT(!cursor.empty());
119 CursorSlice bottom = cursor[0];
120 LyXText * text = bottom.text();
122 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
124 DocIterator it = doc_iterator_begin(cursor.bv().buffer()->inset());
125 DocIterator et = doc_iterator_end(cursor.bv().buffer()->inset());
126 //lyxerr << "x: " << x << " y: " << y << endl;
127 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
128 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
131 //et.par() = text->parOffset(end);
133 double best_dist = 10e10;
134 DocIterator best_cursor = it;
136 for ( ; it != et; it.forwardPos()) {
137 // avoid invalid nesting when selecting
138 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
140 LCursor cur = cursor;
142 cur.inset().getCursorPos(cur, xo, yo);
143 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
144 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
145 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
146 // '<=' in order to take the last possible position
147 // this is important for clicking behind \sum in e.g. '\sum_i a'
148 if (d <= best_dist) {
149 //lyxerr << "*" << endl;
157 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
158 if (best_dist < 1e10)
159 cursor.setCursor(best_cursor);
160 return best_dist < 1e10;
167 LCursor::LCursor(BufferView & bv)
168 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
169 selection_(false), mark_(false)
173 void LCursor::reset(InsetBase & inset)
176 push_back(CursorSlice(inset));
177 anchor_ = DocIterator(inset);
184 // this (intentionally) does neither touch anchor nor selection status
185 void LCursor::setCursor(DocIterator const & cur)
187 DocIterator::operator=(cur);
191 void LCursor::dispatch(FuncRequest const & cmd0)
193 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
197 FuncRequest cmd = cmd0;
198 LCursor safe = *this;
200 for (; size(); pop()) {
201 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
202 BOOST_ASSERT(pos() <= lastpos());
203 BOOST_ASSERT(idx() <= lastidx());
204 BOOST_ASSERT(par() <= lastpar());
206 // The common case is 'LFUN handled, need update', so make the
207 // LFUN handler's life easier by assuming this as default value.
208 // The handler can reset the update and val flags if necessary.
210 disp_.dispatched(true);
211 inset().dispatch(*this, cmd);
212 if (disp_.dispatched())
215 // it completely to get a 'bomb early' behaviour in case this
216 // object will be used again.
217 if (!disp_.dispatched()) {
218 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
220 disp_.dispatched(false);
225 DispatchResult LCursor::result() const
231 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
233 // This is, of course, a mess. Better create a new doc iterator and use
234 // this in Inset::getStatus. This might require an additional
235 // BufferView * arg, though (which should be avoided)
236 LCursor safe = *this;
238 for ( ; size(); pop()) {
239 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
240 if (idx() > lastidx()) {
241 lyxerr << "wrong idx " << idx() << ", max is " << lastidx()
242 << ". Trying to correct this." << endl;
245 if (par() > lastpar()) {
246 lyxerr << "wrong par " << par() << ", max is " << lastpar()
247 << ". Trying to correct this." << endl;
250 if (pos() > lastpos()) {
251 lyxerr << "wrong pos " << pos() << ", max is " << lastpos()
252 << ". Trying to correct this." << endl;
256 // The inset's getStatus() will return 'true' if it made
257 // a definitive decision on whether it want to handle the
258 // request or not. The result of this decision is put into
259 // the 'status' parameter.
260 if (inset().getStatus(*this, cmd, status)) {
270 BufferView & LCursor::bv() const
277 Buffer & LCursor::buffer() const
280 BOOST_ASSERT(bv_->buffer());
281 return *bv_->buffer();
287 BOOST_ASSERT(size() >= 1);
292 void LCursor::push(InsetBase & p)
294 push_back(CursorSlice(p));
298 void LCursor::pushLeft(InsetBase & p)
300 BOOST_ASSERT(!empty());
301 //lyxerr << "Entering inset " << t << " left" << endl;
307 bool LCursor::popLeft()
309 BOOST_ASSERT(!empty());
310 //lyxerr << "Leaving inset to the left" << endl;
311 inset().notifyCursorLeaves(*this);
319 bool LCursor::popRight()
321 BOOST_ASSERT(!empty());
322 //lyxerr << "Leaving inset to the right" << endl;
323 inset().notifyCursorLeaves(*this);
332 int LCursor::currentMode()
334 BOOST_ASSERT(!empty());
335 for (int i = size() - 1; i >= 0; --i) {
336 int res = operator[](i).inset().currentMode();
337 if (res != InsetBase::UNDECIDED_MODE)
340 return InsetBase::TEXT_MODE;
344 void LCursor::getDim(int & asc, int & des) const
347 BOOST_ASSERT(inset().asMathInset());
348 //inset().asMathInset()->getCursorDim(asc, des);
351 } else if (inTexted()) {
352 Row const & row = textRow();
353 asc = row.baseline();
354 des = row.height() - asc;
356 lyxerr << "should this happen?" << endl;
363 void LCursor::getPos(int & x, int & y) const
368 inset().getCursorPos(*this, x, y);
372 void LCursor::paste(string const & data)
374 dispatch(FuncRequest(LFUN_PASTE, data));
378 void LCursor::resetAnchor()
385 bool LCursor::posLeft()
394 bool LCursor::posRight()
396 if (pos() == lastpos())
403 CursorSlice LCursor::anchor() const
405 BOOST_ASSERT(anchor_.size() >= size());
406 CursorSlice normal = anchor_[size() - 1];
407 if (size() < anchor_.size() && back() <= normal) {
408 // anchor is behind cursor -> move anchor behind the inset
415 CursorSlice LCursor::selBegin() const
419 return anchor() < back() ? anchor() : back();
423 CursorSlice LCursor::selEnd() const
427 return anchor() > back() ? anchor() : back();
431 DocIterator LCursor::selectionBegin() const
435 return anchor() < back() ? anchor_ : *this;
439 DocIterator LCursor::selectionEnd() const
443 return anchor() > back() ? anchor_ : *this;
447 void LCursor::setSelection()
450 // a selection with no contents is not a selection
452 #warning doesnt look ok
454 if (par() == anchor().par() && pos() == anchor().pos())
459 void LCursor::setSelection(DocIterator const & where, size_t n)
468 void LCursor::clearSelection()
477 int & LCursor::x_target()
483 int LCursor::x_target() const
489 void LCursor::clearTargetX()
496 void LCursor::info(std::ostream & os) const
498 for (int i = 1, n = depth(); i < n; ++i) {
499 operator[](i).inset().infoize(os);
503 prevInset()->infoize2(os);
504 // overwite old message
509 void LCursor::selHandle(bool sel)
511 //lyxerr << "LCursor::selHandle" << endl;
512 if (sel == selection())
520 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
522 os << "\n cursor: | anchor:\n";
523 for (size_t i = 0, n = cur.size(); i != n; ++i) {
524 os << " " << cur.operator[](i) << " | ";
525 if (i < cur.anchor_.size())
526 os << cur.anchor_[i];
528 os << "-------------------------------";
531 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
532 os << "------------------------------- | " << cur.anchor_[i] << "\n";
534 os << " selection: " << cur.selection_
535 << " x_target: " << cur.x_target_ << endl;
542 ///////////////////////////////////////////////////////////////////
544 // The part below is the non-integrated rest of the original math
545 // cursor. This should be either generalized for texted or moved
546 // back to mathed (in most cases to MathNestInset).
548 ///////////////////////////////////////////////////////////////////
550 #include "mathed/math_charinset.h"
551 #include "mathed/math_factory.h"
552 #include "mathed/math_gridinset.h"
553 #include "mathed/math_macroarg.h"
554 #include "mathed/math_mathmlstream.h"
555 #include "mathed/math_scriptinset.h"
556 #include "mathed/math_support.h"
557 #include "mathed/math_unknowninset.h"
559 //#define FILEDEBUG 1
562 bool LCursor::isInside(InsetBase const * p)
564 for (unsigned i = 0; i < depth(); ++i)
565 if (&operator[](i).inset() == p)
571 bool LCursor::openable(MathAtom const & t) const
582 // we can't move into anything new during selection
583 if (depth() >= anchor_.size())
585 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
592 void LCursor::setScreenPos(int x, int y)
595 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
600 void LCursor::plainErase()
606 void LCursor::markInsert()
612 void LCursor::markErase()
618 void LCursor::plainInsert(MathAtom const & t)
620 cell().insert(pos(), t);
625 void LCursor::insert(string const & str)
627 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
628 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
633 void LCursor::insert(char c)
635 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
636 BOOST_ASSERT(!empty());
638 lyx::cap::selClearOrDel(*this);
639 insert(new MathCharInset(c));
641 text()->insertChar(*this, c);
646 void LCursor::insert(MathAtom const & t)
648 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
650 lyx::cap::selClearOrDel(*this);
655 void LCursor::insert(InsetBase * inset)
658 insert(MathAtom(inset));
660 text()->insertInset(*this, inset);
664 void LCursor::niceInsert(string const & t)
675 void LCursor::niceInsert(MathAtom const & t)
678 string safe = lyx::cap::grabAndEraseSelection(*this);
680 // enter the new inset and move the contents of the selection if possible
683 // be careful here: don't use 'pushLeft(t)' as this we need to
684 // push the clone, not the original
685 pushLeft(*nextInset());
691 void LCursor::insert(MathArray const & ar)
695 lyx::cap::eraseSelection(*this);
696 cell().insert(pos(), ar);
701 bool LCursor::backspace()
703 autocorrect() = false;
706 lyx::cap::selDel(*this);
711 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
718 MathUnknownInset * p = activeMacro();
719 if (p->name().size() > 1) {
720 p->setName(p->name().substr(0, p->name().size() - 1));
725 if (pos() != 0 && prevAtom()->nargs() > 0) {
726 // let's require two backspaces for 'big stuff' and
727 // highlight on the first
739 bool LCursor::erase()
741 autocorrect() = false;
746 lyx::cap::selDel(*this);
750 // delete empty cells if possible
751 if (pos() == lastpos() && inset().idxDelete(idx()))
754 // special behaviour when in last position of cell
755 if (pos() == lastpos()) {
756 bool one_cell = inset().nargs() == 1;
757 if (one_cell && depth() == 1 && lastpos() == 0)
763 inset().idxGlue(idx());
767 // 'clever' UI hack: only erase large items if previously slected
768 if (pos() != lastpos() && inset().nargs() > 0) {
783 DocIterator save = *this;
787 autocorrect() = false;
795 DocIterator save = *this;
799 autocorrect() = false;
804 void LCursor::macroModeClose()
808 MathUnknownInset * p = activeMacro();
810 string s = p->name();
814 // do nothing if the macro name is empty
818 string const name = s.substr(1);
820 // prevent entering of recursive macros
821 // FIXME: this is only a weak attempt... only prevents immediate
823 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
824 if (macro && macro->getInsetName() == name)
825 lyxerr << "can't enter recursive macro" << endl;
827 plainInsert(createMathInset(name));
831 string LCursor::macroName()
833 return inMacroMode() ? activeMacro()->name() : string();
837 void LCursor::handleNest(MathAtom const & a, int c)
839 //lyxerr << "LCursor::handleNest: " << c << endl;
841 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
844 pushLeft(*nextInset());
848 int LCursor::targetX() const
850 if (x_target() != -1)
859 bool LCursor::inMacroMode() const
863 MathUnknownInset const * p = prevAtom()->asUnknownInset();
864 return p && !p->final();
868 MathUnknownInset * LCursor::activeMacro()
870 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
874 void LCursor::pullArg()
879 MathArray ar = cell();
880 if (popLeft() && inMathed()) {
882 cell().insert(pos(), ar);
885 //formula()->mutateToText();
890 void LCursor::touch()
896 DocIterator::const_iterator it = begin();
897 DocIterator::const_iterator et = end();
898 for ( ; it != et; ++it)
904 void LCursor::normalize()
906 if (idx() >= nargs()) {
907 lyxerr << "this should not really happen - 1: "
908 << idx() << ' ' << nargs()
909 << " in: " << &inset() << endl;
911 idx() = min(idx(), lastidx());
913 if (pos() > lastpos()) {
914 lyxerr << "this should not really happen - 2: "
915 << pos() << ' ' << lastpos() << " in idx: " << idx()
917 WriteStream wi(lyxerr, false, true);
918 inset().asMathInset()->write(wi);
921 pos() = min(pos(), lastpos());
925 bool LCursor::goUpDown(bool up)
927 // Be warned: The 'logic' implemented in this function is highly
928 // fragile. A distance of one pixel or a '<' vs '<=' _really
929 // matters. So fiddle around with it only if you think you know
930 // what you are doing!
936 // check if we had something else in mind, if not, this is the future goal
937 if (x_target() == -1)
942 // try neigbouring script insets
946 MathScriptInset const * p = prevAtom()->asScriptInset();
947 if (p && p->has(up)) {
950 idx() = up; // the superscript has index 1
952 //lyxerr << "updown: handled by scriptinset to the left" << endl;
958 if (pos() != lastpos()) {
959 MathScriptInset const * p = nextAtom()->asScriptInset();
960 if (p && p->has(up)) {
964 //lyxerr << "updown: handled by scriptinset to the right" << endl;
970 // try current cell for e.g. text insets
971 if (inset().idxUpDown2(*this, up))
974 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
979 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
980 // lyxerr << "updown: handled by brute find in the same cell" << endl;
984 // try to find an inset that knows better then we
986 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
988 if (inset().idxUpDown(*this, up)) {
989 // try to find best position within this inset
991 setCursor(bruteFind2(*this, xo, yo));
995 // no such inset found, just take something "above"
996 //lyxerr << "updown: handled by strange case" << endl;
998 int ylow = up ? 0 : yo + 1;
999 int yhigh = up ? yo - 1 : bv().workHeight();
1000 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1003 // any improvement so far?
1006 if (up ? ynew < yo : ynew > yo)
1010 // we should not come here.
1011 BOOST_ASSERT(false);
1015 void LCursor::handleFont(string const & font)
1017 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1021 safe = lyx::cap::grabAndEraseSelection(*this);
1024 if (lastpos() != 0) {
1025 // something left in the cell
1027 // cursor in first position
1029 } else if (pos() == lastpos()) {
1030 // cursor in last position
1033 // cursor in between. split cell
1034 MathArray::iterator bt = cell().begin();
1035 MathAtom at = createMathInset(font);
1036 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1037 cell().erase(bt, bt + pos());
1042 // nothing left in the cell
1050 void LCursor::message(string const & msg) const
1052 bv().owner()->getLyXFunc().setMessage(msg);
1056 void LCursor::errorMessage(string const & msg) const
1058 bv().owner()->getLyXFunc().setErrorMessage(msg);
1062 string LCursor::selectionAsString(bool label) const
1068 Buffer const & buffer = *bv().buffer();
1069 ParagraphList & pars = text()->paragraphs();
1071 // should be const ...
1072 par_type startpit = selBegin().par();
1073 par_type endpit = selEnd().par();
1074 size_t const startpos = selBegin().pos();
1075 size_t const endpos = selEnd().pos();
1077 if (startpit == endpit)
1078 return pars[startpit].asString(buffer, startpos, endpos, label);
1080 // First paragraph in selection
1081 string result = pars[startpit].
1082 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1084 // The paragraphs in between (if any)
1085 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1086 Paragraph & par = pars[pit];
1087 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1090 // Last paragraph in selection
1091 result += pars[endpit].asString(buffer, 0, endpos, label);
1096 #ifdef WITH_WARNINGS
1097 #warning and mathed?
1103 string LCursor::currentState()
1106 std::ostringstream os;
1112 return text()->currentState(*this);
1118 string LCursor::getPossibleLabel()
1120 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1124 Encoding const * LCursor::getEncoding() const
1131 // go up until first non-0 text is hit
1132 // (innermost text is 0 in mathed)
1133 for (s = size() - 1; s >= 0; --s)
1134 if (operator[](s).text())
1136 CursorSlice const & sl = operator[](s);
1137 LyXText & text = *sl.text();
1138 LyXFont font = text.getPar(sl.par()).getFont(
1139 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1140 return font.language()->encoding();
1144 void LCursor::undispatched()
1146 disp_.dispatched(false);
1150 void LCursor::dispatched()
1152 disp_.dispatched(true);
1156 void LCursor::needsUpdate()
1162 void LCursor::noUpdate()
1164 disp_.update(false);