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/bind.hpp>
48 #include <boost/current_function.hpp>
57 #ifndef CXX_GLOBAL_CSTD
66 positionable(DocIterator const & cursor, DocIterator const & anchor)
68 // avoid deeper nested insets when selecting
69 if (cursor.size() > anchor.size())
72 // anchor might be deeper, should have same path then
73 for (size_t i = 0; i < cursor.size(); ++i)
74 if (&cursor[i].inset() != &anchor[i].inset())
77 // position should be ok.
82 // Find position closest to (x, y) in cell given by iter.
83 DocIterator bruteFind2(LCursor const & c, int x, int y)
85 double best_dist = 1e10;
92 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
93 for (int i = 0; ; ++i) {
97 cur.inset().getCursorPos(cur, xo, yo);
98 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
99 // '<=' in order to take the last possible position
100 // this is important for clicking behind \sum in e.g. '\sum_i a'
101 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d << " best: " << best_dist << endl;
102 if (d <= best_dist) {
114 /// moves position closest to (x, y) in given box
115 bool bruteFind(LCursor & cursor,
116 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
118 BOOST_ASSERT(!cursor.empty());
120 CursorSlice bottom = cursor[0];
121 LyXText * text = bottom.text();
123 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
125 DocIterator it = doc_iterator_begin(cursor.bv().buffer()->inset());
126 DocIterator et = doc_iterator_end(cursor.bv().buffer()->inset());
127 //lyxerr << "x: " << x << " y: " << y << endl;
128 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
129 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
132 //et.par() = text->parOffset(end);
134 double best_dist = 10e10;
135 DocIterator best_cursor = it;
137 for ( ; it != et; it.forwardPos()) {
138 // avoid invalid nesting when selecting
139 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
141 LCursor cur = cursor;
143 cur.inset().getCursorPos(cur, xo, yo);
144 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
145 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
146 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
147 // '<=' in order to take the last possible position
148 // this is important for clicking behind \sum in e.g. '\sum_i a'
149 if (d <= best_dist) {
150 //lyxerr << "*" << endl;
158 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
159 if (best_dist < 1e10)
160 cursor.setCursor(best_cursor);
161 return best_dist < 1e10;
168 LCursor::LCursor(BufferView & bv)
169 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
170 selection_(false), mark_(false)
174 void LCursor::reset(InsetBase & inset)
177 push_back(CursorSlice(inset));
178 anchor_ = DocIterator(inset);
185 // this (intentionally) does neither touch anchor nor selection status
186 void LCursor::setCursor(DocIterator const & cur)
188 DocIterator::operator=(cur);
192 void LCursor::dispatch(FuncRequest const & cmd0)
194 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
198 FuncRequest cmd = cmd0;
199 LCursor safe = *this;
201 for (; size(); pop()) {
202 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
203 BOOST_ASSERT(pos() <= lastpos());
204 BOOST_ASSERT(idx() <= lastidx());
205 BOOST_ASSERT(par() <= lastpar());
207 // The common case is 'LFUN handled, need update', so make the
208 // LFUN handler's life easier by assuming this as default value.
209 // The handler can reset the update and val flags if necessary.
211 disp_.dispatched(true);
212 inset().dispatch(*this, cmd);
213 if (disp_.dispatched())
216 // it completely to get a 'bomb early' behaviour in case this
217 // object will be used again.
218 if (!disp_.dispatched()) {
219 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
221 disp_.dispatched(false);
226 DispatchResult LCursor::result() const
232 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
234 // This is, of course, a mess. Better create a new doc iterator and use
235 // this in Inset::getStatus. This might require an additional
236 // BufferView * arg, though (which should be avoided)
237 LCursor safe = *this;
239 for ( ; size(); pop()) {
240 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
241 if (idx() > lastidx()) {
242 lyxerr << "wrong idx " << idx() << ", max is " << lastidx()
243 << ". Trying to correct this." << endl;
246 if (par() > lastpar()) {
247 lyxerr << "wrong par " << par() << ", max is " << lastpar()
248 << ". Trying to correct this." << endl;
251 if (pos() > lastpos()) {
252 lyxerr << "wrong pos " << pos() << ", max is " << lastpos()
253 << ". Trying to correct this." << endl;
257 // The inset's getStatus() will return 'true' if it made
258 // a definitive decision on whether it want to handle the
259 // request or not. The result of this decision is put into
260 // the 'status' parameter.
261 if (inset().getStatus(*this, cmd, status)) {
271 BufferView & LCursor::bv() const
278 Buffer & LCursor::buffer() const
281 BOOST_ASSERT(bv_->buffer());
282 return *bv_->buffer();
288 BOOST_ASSERT(size() >= 1);
293 void LCursor::push(InsetBase & p)
295 push_back(CursorSlice(p));
299 void LCursor::pushLeft(InsetBase & p)
301 BOOST_ASSERT(!empty());
302 //lyxerr << "Entering inset " << t << " left" << endl;
308 bool LCursor::popLeft()
310 BOOST_ASSERT(!empty());
311 //lyxerr << "Leaving inset to the left" << endl;
312 inset().notifyCursorLeaves(*this);
320 bool LCursor::popRight()
322 BOOST_ASSERT(!empty());
323 //lyxerr << "Leaving inset to the right" << endl;
324 inset().notifyCursorLeaves(*this);
333 int LCursor::currentMode()
335 BOOST_ASSERT(!empty());
336 for (int i = size() - 1; i >= 0; --i) {
337 int res = operator[](i).inset().currentMode();
338 if (res != InsetBase::UNDECIDED_MODE)
341 return InsetBase::TEXT_MODE;
345 void LCursor::getDim(int & asc, int & des) const
348 BOOST_ASSERT(inset().asMathInset());
349 //inset().asMathInset()->getCursorDim(asc, des);
352 } else if (inTexted()) {
353 Row const & row = textRow();
354 asc = row.baseline();
355 des = row.height() - asc;
357 lyxerr << "should this happen?" << endl;
364 void LCursor::getPos(int & x, int & y) const
369 inset().getCursorPos(*this, x, y);
373 void LCursor::paste(string const & data)
375 dispatch(FuncRequest(LFUN_PASTE, data));
379 void LCursor::resetAnchor()
386 bool LCursor::posLeft()
395 bool LCursor::posRight()
397 if (pos() == lastpos())
404 CursorSlice LCursor::anchor() const
406 BOOST_ASSERT(anchor_.size() >= size());
407 CursorSlice normal = anchor_[size() - 1];
408 if (size() < anchor_.size() && back() <= normal) {
409 // anchor is behind cursor -> move anchor behind the inset
416 CursorSlice LCursor::selBegin() const
420 return anchor() < back() ? anchor() : back();
424 CursorSlice LCursor::selEnd() const
428 return anchor() > back() ? anchor() : back();
432 DocIterator LCursor::selectionBegin() const
436 return anchor() < back() ? anchor_ : *this;
440 DocIterator LCursor::selectionEnd() const
444 return anchor() > back() ? anchor_ : *this;
448 void LCursor::setSelection()
451 // a selection with no contents is not a selection
453 #warning doesnt look ok
455 if (par() == anchor().par() && pos() == anchor().pos())
460 void LCursor::setSelection(DocIterator const & where, size_t n)
469 void LCursor::clearSelection()
478 int & LCursor::x_target()
484 int LCursor::x_target() const
490 void LCursor::clearTargetX()
497 void LCursor::info(std::ostream & os) const
499 for (int i = 1, n = depth(); i < n; ++i) {
500 operator[](i).inset().infoize(os);
504 prevInset()->infoize2(os);
505 // overwite old message
510 void LCursor::selHandle(bool sel)
512 //lyxerr << "LCursor::selHandle" << endl;
513 if (sel == selection())
521 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
523 os << "\n cursor: | anchor:\n";
524 for (size_t i = 0, n = cur.size(); i != n; ++i) {
525 os << " " << cur.operator[](i) << " | ";
526 if (i < cur.anchor_.size())
527 os << cur.anchor_[i];
529 os << "-------------------------------";
532 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
533 os << "------------------------------- | " << cur.anchor_[i] << "\n";
535 os << " selection: " << cur.selection_
536 << " x_target: " << cur.x_target_ << endl;
543 ///////////////////////////////////////////////////////////////////
545 // The part below is the non-integrated rest of the original math
546 // cursor. This should be either generalized for texted or moved
547 // back to mathed (in most cases to MathNestInset).
549 ///////////////////////////////////////////////////////////////////
551 #include "mathed/math_charinset.h"
552 #include "mathed/math_factory.h"
553 #include "mathed/math_gridinset.h"
554 #include "mathed/math_macroarg.h"
555 #include "mathed/math_mathmlstream.h"
556 #include "mathed/math_scriptinset.h"
557 #include "mathed/math_support.h"
558 #include "mathed/math_unknowninset.h"
560 //#define FILEDEBUG 1
563 bool LCursor::isInside(InsetBase const * p)
565 for (unsigned i = 0; i < depth(); ++i)
566 if (&operator[](i).inset() == p)
572 bool LCursor::openable(MathAtom const & t) const
583 // we can't move into anything new during selection
584 if (depth() >= anchor_.size())
586 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
593 void LCursor::setScreenPos(int x, int y)
596 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
601 void LCursor::plainErase()
607 void LCursor::markInsert()
613 void LCursor::markErase()
619 void LCursor::plainInsert(MathAtom const & t)
621 cell().insert(pos(), t);
626 void LCursor::insert(string const & str)
628 for_each(str.begin(), str.end(),
629 boost::bind(static_cast<void(LCursor::*)(char)>
630 (&LCursor::insert), this, _1));
634 void LCursor::insert(char c)
636 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
637 BOOST_ASSERT(!empty());
639 lyx::cap::selClearOrDel(*this);
640 insert(new MathCharInset(c));
642 text()->insertChar(*this, c);
647 void LCursor::insert(MathAtom const & t)
649 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
651 lyx::cap::selClearOrDel(*this);
656 void LCursor::insert(InsetBase * inset)
659 insert(MathAtom(inset));
661 text()->insertInset(*this, inset);
665 void LCursor::niceInsert(string const & t)
676 void LCursor::niceInsert(MathAtom const & t)
679 string safe = lyx::cap::grabAndEraseSelection(*this);
681 // enter the new inset and move the contents of the selection if possible
684 // be careful here: don't use 'pushLeft(t)' as this we need to
685 // push the clone, not the original
686 pushLeft(*nextInset());
692 void LCursor::insert(MathArray const & ar)
696 lyx::cap::eraseSelection(*this);
697 cell().insert(pos(), ar);
702 bool LCursor::backspace()
704 autocorrect() = false;
707 lyx::cap::selDel(*this);
712 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
719 MathUnknownInset * p = activeMacro();
720 if (p->name().size() > 1) {
721 p->setName(p->name().substr(0, p->name().size() - 1));
726 if (pos() != 0 && prevAtom()->nargs() > 0) {
727 // let's require two backspaces for 'big stuff' and
728 // highlight on the first
740 bool LCursor::erase()
742 autocorrect() = false;
747 lyx::cap::selDel(*this);
751 // delete empty cells if possible
752 if (pos() == lastpos() && inset().idxDelete(idx()))
755 // special behaviour when in last position of cell
756 if (pos() == lastpos()) {
757 bool one_cell = inset().nargs() == 1;
758 if (one_cell && depth() == 1 && lastpos() == 0)
764 inset().idxGlue(idx());
768 // 'clever' UI hack: only erase large items if previously slected
769 if (pos() != lastpos() && inset().nargs() > 0) {
784 DocIterator save = *this;
788 autocorrect() = false;
796 DocIterator save = *this;
800 autocorrect() = false;
805 void LCursor::macroModeClose()
809 MathUnknownInset * p = activeMacro();
811 string s = p->name();
815 // do nothing if the macro name is empty
819 string const name = s.substr(1);
821 // prevent entering of recursive macros
822 // FIXME: this is only a weak attempt... only prevents immediate
824 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
825 if (macro && macro->getInsetName() == name)
826 lyxerr << "can't enter recursive macro" << endl;
828 plainInsert(createMathInset(name));
832 string LCursor::macroName()
834 return inMacroMode() ? activeMacro()->name() : string();
838 void LCursor::handleNest(MathAtom const & a, int c)
840 //lyxerr << "LCursor::handleNest: " << c << endl;
842 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
845 pushLeft(*nextInset());
849 int LCursor::targetX() const
851 if (x_target() != -1)
860 bool LCursor::inMacroMode() const
864 MathUnknownInset const * p = prevAtom()->asUnknownInset();
865 return p && !p->final();
869 MathUnknownInset * LCursor::activeMacro()
871 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
875 void LCursor::pullArg()
880 MathArray ar = cell();
881 if (popLeft() && inMathed()) {
883 cell().insert(pos(), ar);
886 //formula()->mutateToText();
891 void LCursor::touch()
897 DocIterator::const_iterator it = begin();
898 DocIterator::const_iterator et = end();
899 for ( ; it != et; ++it)
905 void LCursor::normalize()
907 if (idx() >= nargs()) {
908 lyxerr << "this should not really happen - 1: "
909 << idx() << ' ' << nargs()
910 << " in: " << &inset() << endl;
912 idx() = min(idx(), lastidx());
914 if (pos() > lastpos()) {
915 lyxerr << "this should not really happen - 2: "
916 << pos() << ' ' << lastpos() << " in idx: " << idx()
918 WriteStream wi(lyxerr, false, true);
919 inset().asMathInset()->write(wi);
922 pos() = min(pos(), lastpos());
926 bool LCursor::goUpDown(bool up)
928 // Be warned: The 'logic' implemented in this function is highly
929 // fragile. A distance of one pixel or a '<' vs '<=' _really
930 // matters. So fiddle around with it only if you think you know
931 // what you are doing!
937 // check if we had something else in mind, if not, this is the future goal
938 if (x_target() == -1)
943 // try neigbouring script insets
947 MathScriptInset const * p = prevAtom()->asScriptInset();
948 if (p && p->has(up)) {
951 idx() = up; // the superscript has index 1
953 //lyxerr << "updown: handled by scriptinset to the left" << endl;
959 if (pos() != lastpos()) {
960 MathScriptInset const * p = nextAtom()->asScriptInset();
961 if (p && p->has(up)) {
965 //lyxerr << "updown: handled by scriptinset to the right" << endl;
971 // try current cell for e.g. text insets
972 if (inset().idxUpDown2(*this, up))
975 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
980 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
981 // lyxerr << "updown: handled by brute find in the same cell" << endl;
985 // try to find an inset that knows better then we
987 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
989 if (inset().idxUpDown(*this, up)) {
990 // try to find best position within this inset
992 setCursor(bruteFind2(*this, xo, yo));
996 // no such inset found, just take something "above"
997 //lyxerr << "updown: handled by strange case" << endl;
999 int ylow = up ? 0 : yo + 1;
1000 int yhigh = up ? yo - 1 : bv().workHeight();
1001 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1004 // any improvement so far?
1007 if (up ? ynew < yo : ynew > yo)
1011 // we should not come here.
1012 BOOST_ASSERT(false);
1016 void LCursor::handleFont(string const & font)
1018 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1022 safe = lyx::cap::grabAndEraseSelection(*this);
1025 if (lastpos() != 0) {
1026 // something left in the cell
1028 // cursor in first position
1030 } else if (pos() == lastpos()) {
1031 // cursor in last position
1034 // cursor in between. split cell
1035 MathArray::iterator bt = cell().begin();
1036 MathAtom at = createMathInset(font);
1037 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1038 cell().erase(bt, bt + pos());
1043 // nothing left in the cell
1051 void LCursor::message(string const & msg) const
1053 bv().owner()->getLyXFunc().setMessage(msg);
1057 void LCursor::errorMessage(string const & msg) const
1059 bv().owner()->getLyXFunc().setErrorMessage(msg);
1063 string LCursor::selectionAsString(bool label) const
1069 Buffer const & buffer = *bv().buffer();
1070 ParagraphList & pars = text()->paragraphs();
1072 // should be const ...
1073 par_type startpit = selBegin().par();
1074 par_type endpit = selEnd().par();
1075 size_t const startpos = selBegin().pos();
1076 size_t const endpos = selEnd().pos();
1078 if (startpit == endpit)
1079 return pars[startpit].asString(buffer, startpos, endpos, label);
1081 // First paragraph in selection
1082 string result = pars[startpit].
1083 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1085 // The paragraphs in between (if any)
1086 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1087 Paragraph & par = pars[pit];
1088 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1091 // Last paragraph in selection
1092 result += pars[endpit].asString(buffer, 0, endpos, label);
1097 #ifdef WITH_WARNINGS
1098 #warning and mathed?
1104 string LCursor::currentState()
1107 std::ostringstream os;
1113 return text()->currentState(*this);
1119 string LCursor::getPossibleLabel()
1121 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1125 Encoding const * LCursor::getEncoding() const
1132 // go up until first non-0 text is hit
1133 // (innermost text is 0 in mathed)
1134 for (s = size() - 1; s >= 0; --s)
1135 if (operator[](s).text())
1137 CursorSlice const & sl = operator[](s);
1138 LyXText & text = *sl.text();
1139 LyXFont font = text.getPar(sl.par()).getFont(
1140 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1141 return font.language()->encoding();
1145 void LCursor::undispatched()
1147 disp_.dispatched(false);
1151 void LCursor::dispatched()
1153 disp_.dispatched(true);
1157 void LCursor::needsUpdate()
1163 void LCursor::noUpdate()
1165 disp_.update(false);