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"
43 #include "support/std_sstream.h"
45 #include "frontends/LyXView.h"
47 #include <boost/assert.hpp>
54 #ifndef CXX_GLOBAL_CSTD
61 LCursor::LCursor(BufferView & bv)
62 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
63 selection_(false), mark_(false)
67 void LCursor::reset(InsetBase & inset)
70 push_back(CursorSlice(inset));
71 anchor_ = DocIterator(inset);
78 void LCursor::setCursor(DocIterator const & cur, bool sel)
80 // this (intentionally) does not touch the anchor
81 DocIterator::operator=(cur);
86 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
88 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
90 return DispatchResult();
92 FuncRequest cmd = cmd0;
95 for ( ; size(); pop()) {
96 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
97 BOOST_ASSERT(pos() <= lastpos());
98 BOOST_ASSERT(idx() <= lastidx());
99 BOOST_ASSERT(par() <= lastpar());
101 // The common case is 'LFUN handled, need update', so make the
102 // LFUN handler's life easier by assuming this as default value.
103 // The handler can reset the update and val flags if necessary.
105 disp_.dispatched(true);
106 inset().dispatch(*this, cmd);
107 if (disp_.dispatched())
110 // it completely to get a 'bomb early' behaviour in case this
111 // object will be used again.
112 if (!disp_.dispatched()) {
113 lyxerr << "RESTORING OLD CURSOR!" << endl;
115 disp_.dispatched(false);
121 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
123 // This is, of course, a mess. Better create a new doc iterator and use
124 // this in Inset::getStatus. This might require an additional
125 // BufferView * arg, though (which should be avoided)
126 LCursor safe = *this;
128 for ( ; size(); pop()) {
129 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
130 BOOST_ASSERT(pos() <= lastpos());
131 BOOST_ASSERT(idx() <= lastidx());
132 BOOST_ASSERT(par() <= lastpar());
134 // The inset's getStatus() will return 'true' if it made
135 // a definitive decision on whether it want to handle the
136 // request or not. The result of this decision is put into
137 // the 'status' parameter.
138 if (inset().getStatus(*this, cmd, status)) {
148 BufferView & LCursor::bv() const
155 Buffer & LCursor::buffer() const
158 BOOST_ASSERT(bv_->buffer());
159 return *bv_->buffer();
165 BOOST_ASSERT(size() >= 1);
170 void LCursor::push(InsetBase & p)
172 push_back(CursorSlice(p));
176 void LCursor::pushLeft(InsetBase & p)
178 BOOST_ASSERT(!empty());
179 //lyxerr << "Entering inset " << t << " left" << endl;
185 bool LCursor::popLeft()
187 BOOST_ASSERT(!empty());
188 //lyxerr << "Leaving inset to the left" << endl;
189 inset().notifyCursorLeaves(*this);
197 bool LCursor::popRight()
199 BOOST_ASSERT(!empty());
200 //lyxerr << "Leaving inset to the right" << endl;
201 inset().notifyCursorLeaves(*this);
210 int LCursor::currentMode()
212 BOOST_ASSERT(!empty());
213 for (int i = size() - 1; i >= 0; --i) {
214 int res = operator[](i).inset().currentMode();
215 if (res != InsetBase::UNDECIDED_MODE)
218 return InsetBase::TEXT_MODE;
222 void LCursor::getDim(int & asc, int & des) const
225 BOOST_ASSERT(inset().asMathInset());
226 //inset().asMathInset()->getCursorDim(asc, des);
229 } else if (inTexted()) {
230 Row const & row = textRow();
231 asc = row.baseline();
232 des = row.height() - asc;
234 lyxerr << "should this happen?" << endl;
241 void LCursor::getPos(int & x, int & y) const
246 inset().getCursorPos(*this, x, y);
250 void LCursor::paste(string const & data)
252 dispatch(FuncRequest(LFUN_PASTE, data));
256 void LCursor::resetAnchor()
263 bool LCursor::posLeft()
272 bool LCursor::posRight()
274 if (pos() == lastpos())
281 CursorSlice LCursor::anchor() const
283 BOOST_ASSERT(anchor_.size() >= size());
284 CursorSlice normal = anchor_[size() - 1];
285 if (size() < anchor_.size() && back() <= normal) {
286 // anchor is behind cursor -> move anchor behind the inset
293 CursorSlice LCursor::selBegin() const
297 return anchor() < back() ? anchor() : back();
301 CursorSlice LCursor::selEnd() const
305 return anchor() > back() ? anchor() : back();
309 DocIterator LCursor::selectionBegin() const
313 return anchor() < back() ? anchor_ : *this;
317 DocIterator LCursor::selectionEnd() const
321 return anchor() > back() ? anchor_ : *this;
325 void LCursor::setSelection()
328 // a selection with no contents is not a selection
330 #warning doesnt look ok
332 if (par() == anchor().par() && pos() == anchor().pos())
337 void LCursor::setSelection(DocIterator const & where, size_t n)
339 setCursor(where, true);
345 void LCursor::clearSelection()
354 int & LCursor::x_target()
360 int LCursor::x_target() const
366 void LCursor::clearTargetX()
373 void LCursor::info(std::ostream & os) const
375 for (int i = 1, n = depth(); i < n; ++i) {
376 operator[](i).inset().infoize(os);
380 prevInset()->infoize2(os);
381 // overwite old message
386 void LCursor::selHandle(bool sel)
388 //lyxerr << "LCursor::selHandle" << endl;
389 if (sel == selection())
397 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
399 for (size_t i = 0, n = cur.size(); i != n; ++i) {
400 os << " " << cur.operator[](i) << " | ";
401 if (i < cur.anchor_.size())
402 os << cur.anchor_[i];
404 os << "-------------------------------";
407 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
408 os << "------------------------------- | " << cur.anchor_[i] << "\n";
410 os << " selection: " << cur.selection_
411 << " x_target: " << cur.x_target_ << endl;
418 ///////////////////////////////////////////////////////////////////
420 // The part below is the non-integrated rest of the original math
421 // cursor. This should be either generalized for texted or moved
422 // back to mathed (in most cases to MathNestInset).
424 ///////////////////////////////////////////////////////////////////
426 #include "mathed/math_charinset.h"
427 #include "mathed/math_factory.h"
428 #include "mathed/math_gridinset.h"
429 #include "mathed/math_macroarg.h"
430 #include "mathed/math_mathmlstream.h"
431 #include "mathed/math_scriptinset.h"
432 #include "mathed/math_support.h"
433 #include "mathed/math_unknowninset.h"
435 //#define FILEDEBUG 1
438 bool LCursor::isInside(InsetBase const * p)
440 for (unsigned i = 0; i < depth(); ++i)
441 if (&operator[](i).inset() == p)
447 bool LCursor::openable(MathAtom const & t) const
458 // we can't move into anything new during selection
459 if (depth() >= anchor_.size())
461 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
468 bool positionable(DocIterator const & cursor,
469 DocIterator const & anchor)
471 // avoid deeper nested insets when selecting
472 if (cursor.size() > anchor.size())
475 // anchor might be deeper, should have same path then
476 for (size_t i = 0; i < cursor.size(); ++i)
477 if (&cursor[i].inset() != &anchor[i].inset())
480 // position should be ok.
485 void LCursor::setScreenPos(int x, int y)
488 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
493 void LCursor::plainErase()
499 void LCursor::markInsert()
505 void LCursor::markErase()
511 void LCursor::plainInsert(MathAtom const & t)
513 cell().insert(pos(), t);
518 void LCursor::insert(string const & str)
520 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
521 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
526 void LCursor::insert(char c)
528 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
529 BOOST_ASSERT(!empty());
531 lyx::cap::selClearOrDel(*this);
532 insert(new MathCharInset(c));
534 text()->insertChar(*this, c);
539 void LCursor::insert(MathAtom const & t)
541 //lyxerr << "LCursor::insert MathAtom: " << endl;
543 lyx::cap::selClearOrDel(*this);
545 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
549 void LCursor::insert(InsetBase * inset)
552 insert(MathAtom(inset));
554 text()->insertInset(*this, inset);
558 void LCursor::niceInsert(string const & t)
569 void LCursor::niceInsert(MathAtom const & t)
572 string safe = lyx::cap::grabAndEraseSelection(*this);
574 // enter the new inset and move the contents of the selection if possible
577 // be careful here: don't use 'pushLeft(t)' as this we need to
578 // push the clone, not the original
579 pushLeft(*nextInset());
585 void LCursor::insert(MathArray const & ar)
589 lyx::cap::eraseSelection(*this);
590 cell().insert(pos(), ar);
595 bool LCursor::backspace()
597 autocorrect() = false;
600 lyx::cap::selDel(*this);
605 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
612 MathUnknownInset * p = activeMacro();
613 if (p->name().size() > 1) {
614 p->setName(p->name().substr(0, p->name().size() - 1));
619 if (pos() != 0 && prevAtom()->nargs() > 0) {
620 // let's require two backspaces for 'big stuff' and
621 // highlight on the first
633 bool LCursor::erase()
635 autocorrect() = false;
640 lyx::cap::selDel(*this);
644 // delete empty cells if possible
645 if (pos() == lastpos() && inset().idxDelete(idx()))
648 // special behaviour when in last position of cell
649 if (pos() == lastpos()) {
650 bool one_cell = inset().nargs() == 1;
651 if (one_cell && depth() == 1 && lastpos() == 0)
657 inset().idxGlue(idx());
661 // 'clever' UI hack: only erase large items if previously slected
662 if (pos() != lastpos() && inset().nargs() > 0) {
677 DocIterator save = *this;
680 setCursor(save, false);
681 autocorrect() = false;
689 DocIterator save = *this;
692 setCursor(save, false);
693 autocorrect() = false;
698 void LCursor::macroModeClose()
702 MathUnknownInset * p = activeMacro();
704 string s = p->name();
708 // do nothing if the macro name is empty
712 string const name = s.substr(1);
714 // prevent entering of recursive macros
715 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
716 if (macro && macro->getInsetName() == name)
717 lyxerr << "can't enter recursive macro" << endl;
719 niceInsert(createMathInset(name));
723 string LCursor::macroName()
725 return inMacroMode() ? activeMacro()->name() : string();
729 void LCursor::handleNest(MathAtom const & a, int c)
731 //lyxerr << "LCursor::handleNest: " << c << endl;
733 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
736 pushLeft(*nextInset());
740 int LCursor::targetX() const
742 if (x_target() != -1)
751 bool LCursor::inMacroMode() const
755 MathUnknownInset const * p = prevAtom()->asUnknownInset();
756 return p && !p->final();
760 MathUnknownInset * LCursor::activeMacro()
762 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
766 void LCursor::pullArg()
771 MathArray ar = cell();
772 if (popLeft() && inMathed()) {
774 cell().insert(pos(), ar);
777 //formula()->mutateToText();
782 void LCursor::touch()
788 DocIterator::const_iterator it = begin();
789 DocIterator::const_iterator et = end();
790 for ( ; it != et; ++it)
796 void LCursor::normalize()
798 if (idx() >= nargs()) {
799 lyxerr << "this should not really happen - 1: "
800 << idx() << ' ' << nargs()
801 << " in: " << &inset() << endl;
803 idx() = min(idx(), lastidx());
805 if (pos() > lastpos()) {
806 lyxerr << "this should not really happen - 2: "
807 << pos() << ' ' << lastpos() << " in idx: " << idx()
809 WriteStream wi(lyxerr, false, true);
810 inset().asMathInset()->write(wi);
813 pos() = min(pos(), lastpos());
817 bool LCursor::goUpDown(bool up)
819 // Be warned: The 'logic' implemented in this function is highly
820 // fragile. A distance of one pixel or a '<' vs '<=' _really
821 // matters. So fiddle around with it only if you think you know
822 // what you are doing!
828 // check if we had something else in mind, if not, this is the future goal
829 if (x_target() == -1)
834 // try neigbouring script insets
838 MathScriptInset const * p = prevAtom()->asScriptInset();
839 if (p && p->has(up)) {
842 idx() = up; // the superscript has index 1
844 //lyxerr << "updown: handled by scriptinset to the left" << endl;
850 if (pos() != lastpos()) {
851 MathScriptInset const * p = nextAtom()->asScriptInset();
852 if (p && p->has(up)) {
856 //lyxerr << "updown: handled by scriptinset to the right" << endl;
862 // try current cell for e.g. text insets
863 if (inset().idxUpDown2(*this, up))
866 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
871 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
872 // lyxerr << "updown: handled by brute find in the same cell" << endl;
876 // try to find an inset that knows better then we
878 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
880 if (inset().idxUpDown(*this, up)) {
881 // try to find best position within this inset
887 // no such inset found, just take something "above"
888 //lyxerr << "updown: handled by strange case" << endl;
890 int ylow = up ? 0 : yo + 1;
891 int yhigh = up ? yo - 1 : bv().workHeight();
892 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
895 // any improvement so far?
898 if (up ? ynew < yo : ynew > yo)
904 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
906 BOOST_ASSERT(!empty());
908 CursorSlice bottom = operator[](0);
909 LyXText * text = bottom.text();
911 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
913 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
914 DocIterator et = doc_iterator_end(bv().buffer()->inset());
915 //lyxerr << "x: " << x << " y: " << y << endl;
916 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
917 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
920 //et.par() = text->parOffset(end);
922 double best_dist = 10e10;
923 DocIterator best_cursor = it;
925 for ( ; it != et; it.forwardPos()) {
926 // avoid invalid nesting when selecting
927 if (!selection() || positionable(it, anchor_)) {
930 cur.setCursor(it, false);
931 cur.inset().getCursorPos(cur, xo, yo);
932 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
933 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
934 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
935 // '<=' in order to take the last possible position
936 // this is important for clicking behind \sum in e.g. '\sum_i a'
937 if (d <= best_dist) {
938 //lyxerr << "*" << endl;
946 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
947 if (best_dist < 1e10)
948 setCursor(best_cursor, false);
949 return best_dist < 1e10;
953 void LCursor::bruteFind2(int x, int y)
955 double best_dist = 1e10;
957 DocIterator it = *this;
959 DocIterator et = *this;
960 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
961 for (int i = 0; ; ++i) {
964 cur.setCursor(it, false);
965 cur.inset().getCursorPos(cur, xo, yo);
966 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
967 // '<=' in order to take the last possible position
968 // this is important for clicking behind \sum in e.g. '\sum_i a'
969 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
970 if (d <= best_dist) {
972 setCursor(it, false);
981 void LCursor::handleFont(string const & font)
983 lyxerr << "LCursor::handleFont: " << font << endl;
987 safe = lyx::cap::grabAndEraseSelection(*this);
990 if (lastpos() != 0) {
991 // something left in the cell
993 // cursor in first position
995 } else if (pos() == lastpos()) {
996 // cursor in last position
999 // cursor in between. split cell
1000 MathArray::iterator bt = cell().begin();
1001 MathAtom at = createMathInset(font);
1002 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1003 cell().erase(bt, bt + pos());
1008 // nothing left in the cell
1016 void LCursor::message(string const & msg) const
1018 bv().owner()->getLyXFunc().setMessage(msg);
1022 void LCursor::errorMessage(string const & msg) const
1024 bv().owner()->getLyXFunc().setErrorMessage(msg);
1028 string LCursor::selectionAsString(bool label) const
1034 Buffer const & buffer = *bv().buffer();
1035 ParagraphList & pars = text()->paragraphs();
1037 // should be const ...
1038 par_type startpit = selBegin().par();
1039 par_type endpit = selEnd().par();
1040 size_t const startpos = selBegin().pos();
1041 size_t const endpos = selEnd().pos();
1043 if (startpit == endpit)
1044 return pars[startpit].asString(buffer, startpos, endpos, label);
1046 // First paragraph in selection
1047 string result = pars[startpit].
1048 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1050 // The paragraphs in between (if any)
1051 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1052 Paragraph & par = pars[pit];
1053 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1056 // Last paragraph in selection
1057 result += pars[endpit].asString(buffer, 0, endpos, label);
1062 #ifdef WITH_WARNINGS
1063 #warning and mathed?
1069 string LCursor::currentState()
1072 std::ostringstream os;
1078 return text()->currentState(*this);
1084 string LCursor::getPossibleLabel()
1086 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1090 Encoding const * LCursor::getEncoding() const
1097 // go up until first non-0 text is hit
1098 // (innermost text is 0 in mathed)
1099 for (s = size() - 1; s >= 0; --s)
1100 if (operator[](s).text())
1102 CursorSlice const & sl = operator[](s);
1103 LyXText & text = *sl.text();
1104 LyXFont font = text.getPar(sl.par()).getFont(
1105 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1106 return font.language()->encoding();
1110 void LCursor::undispatched()
1112 disp_.dispatched(false);
1116 void LCursor::dispatched()
1118 disp_.dispatched(true);
1122 void LCursor::noUpdate()
1124 disp_.update(false);