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>
55 #ifndef CXX_GLOBAL_CSTD
64 (DocIterator const & cursor, DocIterator const & anchor)
66 // avoid deeper nested insets when selecting
67 if (cursor.size() > anchor.size())
70 // anchor might be deeper, should have same path then
71 for (size_t i = 0; i < cursor.size(); ++i)
72 if (&cursor[i].inset() != &anchor[i].inset())
75 // position should be ok.
80 // Find position closest to (x, y) in cell given by iter.
81 DocIterator bruteFind2(LCursor const & c, int x, int y)
83 double best_dist = 1e10;
90 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
91 for (int i = 0; ; ++i) {
94 cur.setCursor(it, false);
95 cur.inset().getCursorPos(cur, xo, yo);
96 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
97 // '<=' in order to take the last possible position
98 // this is important for clicking behind \sum in e.g. '\sum_i a'
99 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
100 if (d <= best_dist) {
112 /// moves position closest to (x, y) in given box
113 bool bruteFind(LCursor & cursor,
114 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
116 BOOST_ASSERT(!cursor.empty());
118 CursorSlice bottom = cursor[0];
119 LyXText * text = bottom.text();
121 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
123 DocIterator it = doc_iterator_begin(cursor.bv().buffer()->inset());
124 DocIterator et = doc_iterator_end(cursor.bv().buffer()->inset());
125 //lyxerr << "x: " << x << " y: " << y << endl;
126 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
127 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
130 //et.par() = text->parOffset(end);
132 double best_dist = 10e10;
133 DocIterator best_cursor = it;
135 for ( ; it != et; it.forwardPos()) {
136 // avoid invalid nesting when selecting
137 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
139 LCursor cur = cursor;
140 cur.setCursor(it, false);
141 cur.inset().getCursorPos(cur, xo, yo);
142 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
143 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
144 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
145 // '<=' in order to take the last possible position
146 // this is important for clicking behind \sum in e.g. '\sum_i a'
147 if (d <= best_dist) {
148 //lyxerr << "*" << endl;
156 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
157 if (best_dist < 1e10)
158 cursor.setCursor(best_cursor, false);
159 return best_dist < 1e10;
166 LCursor::LCursor(BufferView & bv)
167 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
168 selection_(false), mark_(false)
172 void LCursor::reset(InsetBase & inset)
175 push_back(CursorSlice(inset));
176 anchor_ = DocIterator(inset);
183 void LCursor::setCursor(DocIterator const & cur, bool sel)
185 // this (intentionally) does not touch the anchor
186 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 << "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 BOOST_ASSERT(pos() <= lastpos());
241 BOOST_ASSERT(idx() <= lastidx());
242 BOOST_ASSERT(par() <= lastpar());
244 // The inset's getStatus() will return 'true' if it made
245 // a definitive decision on whether it want to handle the
246 // request or not. The result of this decision is put into
247 // the 'status' parameter.
248 if (inset().getStatus(*this, cmd, status)) {
258 BufferView & LCursor::bv() const
265 Buffer & LCursor::buffer() const
268 BOOST_ASSERT(bv_->buffer());
269 return *bv_->buffer();
275 BOOST_ASSERT(size() >= 1);
280 void LCursor::push(InsetBase & p)
282 push_back(CursorSlice(p));
286 void LCursor::pushLeft(InsetBase & p)
288 BOOST_ASSERT(!empty());
289 //lyxerr << "Entering inset " << t << " left" << endl;
295 bool LCursor::popLeft()
297 BOOST_ASSERT(!empty());
298 //lyxerr << "Leaving inset to the left" << endl;
299 inset().notifyCursorLeaves(*this);
307 bool LCursor::popRight()
309 BOOST_ASSERT(!empty());
310 //lyxerr << "Leaving inset to the right" << endl;
311 inset().notifyCursorLeaves(*this);
320 int LCursor::currentMode()
322 BOOST_ASSERT(!empty());
323 for (int i = size() - 1; i >= 0; --i) {
324 int res = operator[](i).inset().currentMode();
325 if (res != InsetBase::UNDECIDED_MODE)
328 return InsetBase::TEXT_MODE;
332 void LCursor::getDim(int & asc, int & des) const
335 BOOST_ASSERT(inset().asMathInset());
336 //inset().asMathInset()->getCursorDim(asc, des);
339 } else if (inTexted()) {
340 Row const & row = textRow();
341 asc = row.baseline();
342 des = row.height() - asc;
344 lyxerr << "should this happen?" << endl;
351 void LCursor::getPos(int & x, int & y) const
356 inset().getCursorPos(*this, x, y);
360 void LCursor::paste(string const & data)
362 dispatch(FuncRequest(LFUN_PASTE, data));
366 void LCursor::resetAnchor()
373 bool LCursor::posLeft()
382 bool LCursor::posRight()
384 if (pos() == lastpos())
391 CursorSlice LCursor::anchor() const
393 BOOST_ASSERT(anchor_.size() >= size());
394 CursorSlice normal = anchor_[size() - 1];
395 if (size() < anchor_.size() && back() <= normal) {
396 // anchor is behind cursor -> move anchor behind the inset
403 CursorSlice LCursor::selBegin() const
407 return anchor() < back() ? anchor() : back();
411 CursorSlice LCursor::selEnd() const
415 return anchor() > back() ? anchor() : back();
419 DocIterator LCursor::selectionBegin() const
423 return anchor() < back() ? anchor_ : *this;
427 DocIterator LCursor::selectionEnd() const
431 return anchor() > back() ? anchor_ : *this;
435 void LCursor::setSelection()
438 // a selection with no contents is not a selection
440 #warning doesnt look ok
442 if (par() == anchor().par() && pos() == anchor().pos())
447 void LCursor::setSelection(DocIterator const & where, size_t n)
449 setCursor(where, true);
455 void LCursor::clearSelection()
464 int & LCursor::x_target()
470 int LCursor::x_target() const
476 void LCursor::clearTargetX()
483 void LCursor::info(std::ostream & os) const
485 for (int i = 1, n = depth(); i < n; ++i) {
486 operator[](i).inset().infoize(os);
490 prevInset()->infoize2(os);
491 // overwite old message
496 void LCursor::selHandle(bool sel)
498 //lyxerr << "LCursor::selHandle" << endl;
499 if (sel == selection())
507 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
509 os << "\n cursor: | anchor:\n";
510 for (size_t i = 0, n = cur.size(); i != n; ++i) {
511 os << " " << cur.operator[](i) << " | ";
512 if (i < cur.anchor_.size())
513 os << cur.anchor_[i];
515 os << "-------------------------------";
518 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
519 os << "------------------------------- | " << cur.anchor_[i] << "\n";
521 os << " selection: " << cur.selection_
522 << " x_target: " << cur.x_target_ << endl;
529 ///////////////////////////////////////////////////////////////////
531 // The part below is the non-integrated rest of the original math
532 // cursor. This should be either generalized for texted or moved
533 // back to mathed (in most cases to MathNestInset).
535 ///////////////////////////////////////////////////////////////////
537 #include "mathed/math_charinset.h"
538 #include "mathed/math_factory.h"
539 #include "mathed/math_gridinset.h"
540 #include "mathed/math_macroarg.h"
541 #include "mathed/math_mathmlstream.h"
542 #include "mathed/math_scriptinset.h"
543 #include "mathed/math_support.h"
544 #include "mathed/math_unknowninset.h"
546 //#define FILEDEBUG 1
549 bool LCursor::isInside(InsetBase const * p)
551 for (unsigned i = 0; i < depth(); ++i)
552 if (&operator[](i).inset() == p)
558 bool LCursor::openable(MathAtom const & t) const
569 // we can't move into anything new during selection
570 if (depth() >= anchor_.size())
572 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
579 void LCursor::setScreenPos(int x, int y)
582 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
587 void LCursor::plainErase()
593 void LCursor::markInsert()
599 void LCursor::markErase()
605 void LCursor::plainInsert(MathAtom const & t)
607 cell().insert(pos(), t);
612 void LCursor::insert(string const & str)
614 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
615 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
620 void LCursor::insert(char c)
622 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
623 BOOST_ASSERT(!empty());
625 lyx::cap::selClearOrDel(*this);
626 insert(new MathCharInset(c));
628 text()->insertChar(*this, c);
633 void LCursor::insert(MathAtom const & t)
635 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
637 lyx::cap::selClearOrDel(*this);
642 void LCursor::insert(InsetBase * inset)
645 insert(MathAtom(inset));
647 text()->insertInset(*this, inset);
651 void LCursor::niceInsert(string const & t)
662 void LCursor::niceInsert(MathAtom const & t)
665 string safe = lyx::cap::grabAndEraseSelection(*this);
667 // enter the new inset and move the contents of the selection if possible
670 // be careful here: don't use 'pushLeft(t)' as this we need to
671 // push the clone, not the original
672 pushLeft(*nextInset());
678 void LCursor::insert(MathArray const & ar)
682 lyx::cap::eraseSelection(*this);
683 cell().insert(pos(), ar);
688 bool LCursor::backspace()
690 autocorrect() = false;
693 lyx::cap::selDel(*this);
698 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
705 MathUnknownInset * p = activeMacro();
706 if (p->name().size() > 1) {
707 p->setName(p->name().substr(0, p->name().size() - 1));
712 if (pos() != 0 && prevAtom()->nargs() > 0) {
713 // let's require two backspaces for 'big stuff' and
714 // highlight on the first
726 bool LCursor::erase()
728 autocorrect() = false;
733 lyx::cap::selDel(*this);
737 // delete empty cells if possible
738 if (pos() == lastpos() && inset().idxDelete(idx()))
741 // special behaviour when in last position of cell
742 if (pos() == lastpos()) {
743 bool one_cell = inset().nargs() == 1;
744 if (one_cell && depth() == 1 && lastpos() == 0)
750 inset().idxGlue(idx());
754 // 'clever' UI hack: only erase large items if previously slected
755 if (pos() != lastpos() && inset().nargs() > 0) {
770 DocIterator save = *this;
773 setCursor(save, false);
774 autocorrect() = false;
782 DocIterator save = *this;
785 setCursor(save, false);
786 autocorrect() = false;
791 void LCursor::macroModeClose()
795 MathUnknownInset * p = activeMacro();
797 string s = p->name();
801 // do nothing if the macro name is empty
805 string const name = s.substr(1);
807 // prevent entering of recursive macros
808 // FIXME: this is only a weak attempt... only prevents immediate
810 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
811 if (macro && macro->getInsetName() == name)
812 lyxerr << "can't enter recursive macro" << endl;
814 plainInsert(createMathInset(name));
818 string LCursor::macroName()
820 return inMacroMode() ? activeMacro()->name() : string();
824 void LCursor::handleNest(MathAtom const & a, int c)
826 //lyxerr << "LCursor::handleNest: " << c << endl;
828 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
831 pushLeft(*nextInset());
835 int LCursor::targetX() const
837 if (x_target() != -1)
846 bool LCursor::inMacroMode() const
850 MathUnknownInset const * p = prevAtom()->asUnknownInset();
851 return p && !p->final();
855 MathUnknownInset * LCursor::activeMacro()
857 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
861 void LCursor::pullArg()
866 MathArray ar = cell();
867 if (popLeft() && inMathed()) {
869 cell().insert(pos(), ar);
872 //formula()->mutateToText();
877 void LCursor::touch()
883 DocIterator::const_iterator it = begin();
884 DocIterator::const_iterator et = end();
885 for ( ; it != et; ++it)
891 void LCursor::normalize()
893 if (idx() >= nargs()) {
894 lyxerr << "this should not really happen - 1: "
895 << idx() << ' ' << nargs()
896 << " in: " << &inset() << endl;
898 idx() = min(idx(), lastidx());
900 if (pos() > lastpos()) {
901 lyxerr << "this should not really happen - 2: "
902 << pos() << ' ' << lastpos() << " in idx: " << idx()
904 WriteStream wi(lyxerr, false, true);
905 inset().asMathInset()->write(wi);
908 pos() = min(pos(), lastpos());
912 bool LCursor::goUpDown(bool up)
914 // Be warned: The 'logic' implemented in this function is highly
915 // fragile. A distance of one pixel or a '<' vs '<=' _really
916 // matters. So fiddle around with it only if you think you know
917 // what you are doing!
923 // check if we had something else in mind, if not, this is the future goal
924 if (x_target() == -1)
929 // try neigbouring script insets
933 MathScriptInset const * p = prevAtom()->asScriptInset();
934 if (p && p->has(up)) {
937 idx() = up; // the superscript has index 1
939 //lyxerr << "updown: handled by scriptinset to the left" << endl;
945 if (pos() != lastpos()) {
946 MathScriptInset const * p = nextAtom()->asScriptInset();
947 if (p && p->has(up)) {
951 //lyxerr << "updown: handled by scriptinset to the right" << endl;
957 // try current cell for e.g. text insets
958 if (inset().idxUpDown2(*this, up))
961 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
966 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
967 // lyxerr << "updown: handled by brute find in the same cell" << endl;
971 // try to find an inset that knows better then we
973 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
975 if (inset().idxUpDown(*this, up)) {
976 // try to find best position within this inset
978 setCursor(bruteFind2(*this, xo, yo), false);
982 // no such inset found, just take something "above"
983 //lyxerr << "updown: handled by strange case" << endl;
985 int ylow = up ? 0 : yo + 1;
986 int yhigh = up ? yo - 1 : bv().workHeight();
987 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
990 // any improvement so far?
993 if (up ? ynew < yo : ynew > yo)
997 // we should not come here.
1002 void LCursor::handleFont(string const & font)
1004 lyxerr << "LCursor::handleFont: " << font << endl;
1008 safe = lyx::cap::grabAndEraseSelection(*this);
1011 if (lastpos() != 0) {
1012 // something left in the cell
1014 // cursor in first position
1016 } else if (pos() == lastpos()) {
1017 // cursor in last position
1020 // cursor in between. split cell
1021 MathArray::iterator bt = cell().begin();
1022 MathAtom at = createMathInset(font);
1023 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1024 cell().erase(bt, bt + pos());
1029 // nothing left in the cell
1037 void LCursor::message(string const & msg) const
1039 bv().owner()->getLyXFunc().setMessage(msg);
1043 void LCursor::errorMessage(string const & msg) const
1045 bv().owner()->getLyXFunc().setErrorMessage(msg);
1049 string LCursor::selectionAsString(bool label) const
1055 Buffer const & buffer = *bv().buffer();
1056 ParagraphList & pars = text()->paragraphs();
1058 // should be const ...
1059 par_type startpit = selBegin().par();
1060 par_type endpit = selEnd().par();
1061 size_t const startpos = selBegin().pos();
1062 size_t const endpos = selEnd().pos();
1064 if (startpit == endpit)
1065 return pars[startpit].asString(buffer, startpos, endpos, label);
1067 // First paragraph in selection
1068 string result = pars[startpit].
1069 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1071 // The paragraphs in between (if any)
1072 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1073 Paragraph & par = pars[pit];
1074 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1077 // Last paragraph in selection
1078 result += pars[endpit].asString(buffer, 0, endpos, label);
1083 #ifdef WITH_WARNINGS
1084 #warning and mathed?
1090 string LCursor::currentState()
1093 std::ostringstream os;
1099 return text()->currentState(*this);
1105 string LCursor::getPossibleLabel()
1107 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1111 Encoding const * LCursor::getEncoding() const
1118 // go up until first non-0 text is hit
1119 // (innermost text is 0 in mathed)
1120 for (s = size() - 1; s >= 0; --s)
1121 if (operator[](s).text())
1123 CursorSlice const & sl = operator[](s);
1124 LyXText & text = *sl.text();
1125 LyXFont font = text.getPar(sl.par()).getFont(
1126 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1127 return font.language()->encoding();
1131 void LCursor::undispatched()
1133 disp_.dispatched(false);
1137 void LCursor::dispatched()
1139 disp_.dispatched(true);
1143 void LCursor::needsUpdate()
1149 void LCursor::noUpdate()
1151 disp_.update(false);