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 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)
456 void LCursor::clearSelection()
465 int & LCursor::x_target()
471 int LCursor::x_target() const
477 void LCursor::clearTargetX()
484 void LCursor::info(std::ostream & os) const
486 for (int i = 1, n = depth(); i < n; ++i) {
487 operator[](i).inset().infoize(os);
491 prevInset()->infoize2(os);
492 // overwite old message
497 void LCursor::selHandle(bool sel)
499 //lyxerr << "LCursor::selHandle" << endl;
500 if (sel == selection())
508 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
510 os << "\n cursor: | anchor:\n";
511 for (size_t i = 0, n = cur.size(); i != n; ++i) {
512 os << " " << cur.operator[](i) << " | ";
513 if (i < cur.anchor_.size())
514 os << cur.anchor_[i];
516 os << "-------------------------------";
519 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
520 os << "------------------------------- | " << cur.anchor_[i] << "\n";
522 os << " selection: " << cur.selection_
523 << " x_target: " << cur.x_target_ << endl;
530 ///////////////////////////////////////////////////////////////////
532 // The part below is the non-integrated rest of the original math
533 // cursor. This should be either generalized for texted or moved
534 // back to mathed (in most cases to MathNestInset).
536 ///////////////////////////////////////////////////////////////////
538 #include "mathed/math_charinset.h"
539 #include "mathed/math_factory.h"
540 #include "mathed/math_gridinset.h"
541 #include "mathed/math_macroarg.h"
542 #include "mathed/math_mathmlstream.h"
543 #include "mathed/math_scriptinset.h"
544 #include "mathed/math_support.h"
545 #include "mathed/math_unknowninset.h"
547 //#define FILEDEBUG 1
550 bool LCursor::isInside(InsetBase const * p)
552 for (unsigned i = 0; i < depth(); ++i)
553 if (&operator[](i).inset() == p)
559 bool LCursor::openable(MathAtom const & t) const
570 // we can't move into anything new during selection
571 if (depth() >= anchor_.size())
573 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
580 void LCursor::setScreenPos(int x, int y)
583 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
588 void LCursor::plainErase()
594 void LCursor::markInsert()
600 void LCursor::markErase()
606 void LCursor::plainInsert(MathAtom const & t)
608 cell().insert(pos(), t);
613 void LCursor::insert(string const & str)
615 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
616 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
621 void LCursor::insert(char c)
623 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
624 BOOST_ASSERT(!empty());
626 lyx::cap::selClearOrDel(*this);
627 insert(new MathCharInset(c));
629 text()->insertChar(*this, c);
634 void LCursor::insert(MathAtom const & t)
636 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
638 lyx::cap::selClearOrDel(*this);
643 void LCursor::insert(InsetBase * inset)
646 insert(MathAtom(inset));
648 text()->insertInset(*this, inset);
652 void LCursor::niceInsert(string const & t)
663 void LCursor::niceInsert(MathAtom const & t)
666 string safe = lyx::cap::grabAndEraseSelection(*this);
668 // enter the new inset and move the contents of the selection if possible
671 // be careful here: don't use 'pushLeft(t)' as this we need to
672 // push the clone, not the original
673 pushLeft(*nextInset());
679 void LCursor::insert(MathArray const & ar)
683 lyx::cap::eraseSelection(*this);
684 cell().insert(pos(), ar);
689 bool LCursor::backspace()
691 autocorrect() = false;
694 lyx::cap::selDel(*this);
699 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
706 MathUnknownInset * p = activeMacro();
707 if (p->name().size() > 1) {
708 p->setName(p->name().substr(0, p->name().size() - 1));
713 if (pos() != 0 && prevAtom()->nargs() > 0) {
714 // let's require two backspaces for 'big stuff' and
715 // highlight on the first
727 bool LCursor::erase()
729 autocorrect() = false;
734 lyx::cap::selDel(*this);
738 // delete empty cells if possible
739 if (pos() == lastpos() && inset().idxDelete(idx()))
742 // special behaviour when in last position of cell
743 if (pos() == lastpos()) {
744 bool one_cell = inset().nargs() == 1;
745 if (one_cell && depth() == 1 && lastpos() == 0)
751 inset().idxGlue(idx());
755 // 'clever' UI hack: only erase large items if previously slected
756 if (pos() != lastpos() && inset().nargs() > 0) {
771 DocIterator save = *this;
775 autocorrect() = false;
783 DocIterator save = *this;
787 autocorrect() = false;
792 void LCursor::macroModeClose()
796 MathUnknownInset * p = activeMacro();
798 string s = p->name();
802 // do nothing if the macro name is empty
806 string const name = s.substr(1);
808 // prevent entering of recursive macros
809 // FIXME: this is only a weak attempt... only prevents immediate
811 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
812 if (macro && macro->getInsetName() == name)
813 lyxerr << "can't enter recursive macro" << endl;
815 plainInsert(createMathInset(name));
819 string LCursor::macroName()
821 return inMacroMode() ? activeMacro()->name() : string();
825 void LCursor::handleNest(MathAtom const & a, int c)
827 //lyxerr << "LCursor::handleNest: " << c << endl;
829 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
832 pushLeft(*nextInset());
836 int LCursor::targetX() const
838 if (x_target() != -1)
847 bool LCursor::inMacroMode() const
851 MathUnknownInset const * p = prevAtom()->asUnknownInset();
852 return p && !p->final();
856 MathUnknownInset * LCursor::activeMacro()
858 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
862 void LCursor::pullArg()
867 MathArray ar = cell();
868 if (popLeft() && inMathed()) {
870 cell().insert(pos(), ar);
873 //formula()->mutateToText();
878 void LCursor::touch()
884 DocIterator::const_iterator it = begin();
885 DocIterator::const_iterator et = end();
886 for ( ; it != et; ++it)
892 void LCursor::normalize()
894 if (idx() >= nargs()) {
895 lyxerr << "this should not really happen - 1: "
896 << idx() << ' ' << nargs()
897 << " in: " << &inset() << endl;
899 idx() = min(idx(), lastidx());
901 if (pos() > lastpos()) {
902 lyxerr << "this should not really happen - 2: "
903 << pos() << ' ' << lastpos() << " in idx: " << idx()
905 WriteStream wi(lyxerr, false, true);
906 inset().asMathInset()->write(wi);
909 pos() = min(pos(), lastpos());
913 bool LCursor::goUpDown(bool up)
915 // Be warned: The 'logic' implemented in this function is highly
916 // fragile. A distance of one pixel or a '<' vs '<=' _really
917 // matters. So fiddle around with it only if you think you know
918 // what you are doing!
924 // check if we had something else in mind, if not, this is the future goal
925 if (x_target() == -1)
930 // try neigbouring script insets
934 MathScriptInset const * p = prevAtom()->asScriptInset();
935 if (p && p->has(up)) {
938 idx() = up; // the superscript has index 1
940 //lyxerr << "updown: handled by scriptinset to the left" << endl;
946 if (pos() != lastpos()) {
947 MathScriptInset const * p = nextAtom()->asScriptInset();
948 if (p && p->has(up)) {
952 //lyxerr << "updown: handled by scriptinset to the right" << endl;
958 // try current cell for e.g. text insets
959 if (inset().idxUpDown2(*this, up))
962 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
967 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
968 // lyxerr << "updown: handled by brute find in the same cell" << endl;
972 // try to find an inset that knows better then we
974 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
976 if (inset().idxUpDown(*this, up)) {
977 // try to find best position within this inset
979 setCursor(bruteFind2(*this, xo, yo));
983 // no such inset found, just take something "above"
984 //lyxerr << "updown: handled by strange case" << endl;
986 int ylow = up ? 0 : yo + 1;
987 int yhigh = up ? yo - 1 : bv().workHeight();
988 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
991 // any improvement so far?
994 if (up ? ynew < yo : ynew > yo)
998 // we should not come here.
1003 void LCursor::handleFont(string const & font)
1005 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1009 safe = lyx::cap::grabAndEraseSelection(*this);
1012 if (lastpos() != 0) {
1013 // something left in the cell
1015 // cursor in first position
1017 } else if (pos() == lastpos()) {
1018 // cursor in last position
1021 // cursor in between. split cell
1022 MathArray::iterator bt = cell().begin();
1023 MathAtom at = createMathInset(font);
1024 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1025 cell().erase(bt, bt + pos());
1030 // nothing left in the cell
1038 void LCursor::message(string const & msg) const
1040 bv().owner()->getLyXFunc().setMessage(msg);
1044 void LCursor::errorMessage(string const & msg) const
1046 bv().owner()->getLyXFunc().setErrorMessage(msg);
1050 string LCursor::selectionAsString(bool label) const
1056 Buffer const & buffer = *bv().buffer();
1057 ParagraphList & pars = text()->paragraphs();
1059 // should be const ...
1060 par_type startpit = selBegin().par();
1061 par_type endpit = selEnd().par();
1062 size_t const startpos = selBegin().pos();
1063 size_t const endpos = selEnd().pos();
1065 if (startpit == endpit)
1066 return pars[startpit].asString(buffer, startpos, endpos, label);
1068 // First paragraph in selection
1069 string result = pars[startpit].
1070 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1072 // The paragraphs in between (if any)
1073 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1074 Paragraph & par = pars[pit];
1075 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1078 // Last paragraph in selection
1079 result += pars[endpit].asString(buffer, 0, endpos, label);
1084 #ifdef WITH_WARNINGS
1085 #warning and mathed?
1091 string LCursor::currentState()
1094 std::ostringstream os;
1100 return text()->currentState(*this);
1106 string LCursor::getPossibleLabel()
1108 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1112 Encoding const * LCursor::getEncoding() const
1119 // go up until first non-0 text is hit
1120 // (innermost text is 0 in mathed)
1121 for (s = size() - 1; s >= 0; --s)
1122 if (operator[](s).text())
1124 CursorSlice const & sl = operator[](s);
1125 LyXText & text = *sl.text();
1126 LyXFont font = text.getPar(sl.par()).getFont(
1127 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1128 return font.language()->encoding();
1132 void LCursor::undispatched()
1134 disp_.dispatched(false);
1138 void LCursor::dispatched()
1140 disp_.dispatched(true);
1144 void LCursor::needsUpdate()
1150 void LCursor::noUpdate()
1152 disp_.update(false);