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
62 LCursor::LCursor(BufferView & bv)
63 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
64 selection_(false), mark_(false)
68 void LCursor::reset(InsetBase & inset)
71 push_back(CursorSlice(inset));
72 anchor_ = DocIterator(inset);
79 void LCursor::setCursor(DocIterator const & cur, bool sel)
81 // this (intentionally) does not touch the anchor
82 DocIterator::operator=(cur);
87 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
89 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
91 return DispatchResult();
93 FuncRequest cmd = cmd0;
96 for ( ; size(); pop()) {
97 lyxerr << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
98 BOOST_ASSERT(pos() <= lastpos());
99 BOOST_ASSERT(idx() <= lastidx());
100 BOOST_ASSERT(par() <= lastpar());
102 // The common case is 'LFUN handled, need update', so make the
103 // LFUN handler's life easier by assuming this as default value.
104 // The handler can reset the update and val flags if necessary.
106 disp_.dispatched(true);
107 inset().dispatch(*this, cmd);
108 if (disp_.dispatched())
111 // it completely to get a 'bomb early' behaviour in case this
112 // object will be used again.
113 if (!disp_.dispatched()) {
114 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
116 disp_.dispatched(false);
122 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
124 // This is, of course, a mess. Better create a new doc iterator and use
125 // this in Inset::getStatus. This might require an additional
126 // BufferView * arg, though (which should be avoided)
127 LCursor safe = *this;
129 for ( ; size(); pop()) {
130 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
131 BOOST_ASSERT(pos() <= lastpos());
132 BOOST_ASSERT(idx() <= lastidx());
133 BOOST_ASSERT(par() <= lastpar());
135 // The inset's getStatus() will return 'true' if it made
136 // a definitive decision on whether it want to handle the
137 // request or not. The result of this decision is put into
138 // the 'status' parameter.
139 if (inset().getStatus(*this, cmd, status)) {
149 BufferView & LCursor::bv() const
156 Buffer & LCursor::buffer() const
159 BOOST_ASSERT(bv_->buffer());
160 return *bv_->buffer();
166 BOOST_ASSERT(size() >= 1);
171 void LCursor::push(InsetBase & p)
173 push_back(CursorSlice(p));
177 void LCursor::pushLeft(InsetBase & p)
179 BOOST_ASSERT(!empty());
180 //lyxerr << "Entering inset " << t << " left" << endl;
186 bool LCursor::popLeft()
188 BOOST_ASSERT(!empty());
189 //lyxerr << "Leaving inset to the left" << endl;
190 inset().notifyCursorLeaves(*this);
198 bool LCursor::popRight()
200 BOOST_ASSERT(!empty());
201 //lyxerr << "Leaving inset to the right" << endl;
202 inset().notifyCursorLeaves(*this);
211 int LCursor::currentMode()
213 BOOST_ASSERT(!empty());
214 for (int i = size() - 1; i >= 0; --i) {
215 int res = operator[](i).inset().currentMode();
216 if (res != InsetBase::UNDECIDED_MODE)
219 return InsetBase::TEXT_MODE;
223 void LCursor::getDim(int & asc, int & des) const
226 BOOST_ASSERT(inset().asMathInset());
227 //inset().asMathInset()->getCursorDim(asc, des);
230 } else if (inTexted()) {
231 Row const & row = textRow();
232 asc = row.baseline();
233 des = row.height() - asc;
235 lyxerr << "should this happen?" << endl;
242 void LCursor::getPos(int & x, int & y) const
247 inset().getCursorPos(*this, x, y);
251 void LCursor::paste(string const & data)
253 dispatch(FuncRequest(LFUN_PASTE, data));
257 void LCursor::resetAnchor()
264 bool LCursor::posLeft()
273 bool LCursor::posRight()
275 if (pos() == lastpos())
282 CursorSlice LCursor::anchor() const
284 BOOST_ASSERT(anchor_.size() >= size());
285 CursorSlice normal = anchor_[size() - 1];
286 if (size() < anchor_.size() && back() <= normal) {
287 // anchor is behind cursor -> move anchor behind the inset
294 CursorSlice LCursor::selBegin() const
298 return anchor() < back() ? anchor() : back();
302 CursorSlice LCursor::selEnd() const
306 return anchor() > back() ? anchor() : back();
310 DocIterator LCursor::selectionBegin() const
314 return anchor() < back() ? anchor_ : *this;
318 DocIterator LCursor::selectionEnd() const
322 return anchor() > back() ? anchor_ : *this;
326 void LCursor::setSelection()
329 // a selection with no contents is not a selection
331 #warning doesnt look ok
333 if (par() == anchor().par() && pos() == anchor().pos())
338 void LCursor::setSelection(DocIterator const & where, size_t n)
340 setCursor(where, true);
346 void LCursor::clearSelection()
355 int & LCursor::x_target()
361 int LCursor::x_target() const
367 void LCursor::clearTargetX()
374 void LCursor::info(std::ostream & os) const
376 for (int i = 1, n = depth(); i < n; ++i) {
377 operator[](i).inset().infoize(os);
381 prevInset()->infoize2(os);
382 // overwite old message
387 void LCursor::selHandle(bool sel)
389 //lyxerr << "LCursor::selHandle" << endl;
390 if (sel == selection())
398 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
400 os << "\n cursor: | anchor:\n";
401 for (size_t i = 0, n = cur.size(); i != n; ++i) {
402 os << " " << cur.operator[](i) << " | ";
403 if (i < cur.anchor_.size())
404 os << cur.anchor_[i];
406 os << "-------------------------------";
409 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
410 os << "------------------------------- | " << cur.anchor_[i] << "\n";
412 os << " selection: " << cur.selection_
413 << " x_target: " << cur.x_target_ << endl;
420 ///////////////////////////////////////////////////////////////////
422 // The part below is the non-integrated rest of the original math
423 // cursor. This should be either generalized for texted or moved
424 // back to mathed (in most cases to MathNestInset).
426 ///////////////////////////////////////////////////////////////////
428 #include "mathed/math_charinset.h"
429 #include "mathed/math_factory.h"
430 #include "mathed/math_gridinset.h"
431 #include "mathed/math_macroarg.h"
432 #include "mathed/math_mathmlstream.h"
433 #include "mathed/math_scriptinset.h"
434 #include "mathed/math_support.h"
435 #include "mathed/math_unknowninset.h"
437 //#define FILEDEBUG 1
440 bool LCursor::isInside(InsetBase const * p)
442 for (unsigned i = 0; i < depth(); ++i)
443 if (&operator[](i).inset() == p)
449 bool LCursor::openable(MathAtom const & t) const
460 // we can't move into anything new during selection
461 if (depth() >= anchor_.size())
463 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
470 bool positionable(DocIterator const & cursor,
471 DocIterator const & anchor)
473 // avoid deeper nested insets when selecting
474 if (cursor.size() > anchor.size())
477 // anchor might be deeper, should have same path then
478 for (size_t i = 0; i < cursor.size(); ++i)
479 if (&cursor[i].inset() != &anchor[i].inset())
482 // position should be ok.
487 void LCursor::setScreenPos(int x, int y)
490 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
495 void LCursor::plainErase()
501 void LCursor::markInsert()
507 void LCursor::markErase()
513 void LCursor::plainInsert(MathAtom const & t)
515 cell().insert(pos(), t);
520 void LCursor::insert(string const & str)
522 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
523 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
528 void LCursor::insert(char c)
530 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
531 BOOST_ASSERT(!empty());
533 lyx::cap::selClearOrDel(*this);
534 insert(new MathCharInset(c));
536 text()->insertChar(*this, c);
541 void LCursor::insert(MathAtom const & t)
543 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
545 lyx::cap::selClearOrDel(*this);
550 void LCursor::insert(InsetBase * inset)
553 insert(MathAtom(inset));
555 text()->insertInset(*this, inset);
559 void LCursor::niceInsert(string const & t)
570 void LCursor::niceInsert(MathAtom const & t)
573 string safe = lyx::cap::grabAndEraseSelection(*this);
575 // enter the new inset and move the contents of the selection if possible
578 // be careful here: don't use 'pushLeft(t)' as this we need to
579 // push the clone, not the original
580 pushLeft(*nextInset());
586 void LCursor::insert(MathArray const & ar)
590 lyx::cap::eraseSelection(*this);
591 cell().insert(pos(), ar);
596 bool LCursor::backspace()
598 autocorrect() = false;
601 lyx::cap::selDel(*this);
606 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
613 MathUnknownInset * p = activeMacro();
614 if (p->name().size() > 1) {
615 p->setName(p->name().substr(0, p->name().size() - 1));
620 if (pos() != 0 && prevAtom()->nargs() > 0) {
621 // let's require two backspaces for 'big stuff' and
622 // highlight on the first
634 bool LCursor::erase()
636 autocorrect() = false;
641 lyx::cap::selDel(*this);
645 // delete empty cells if possible
646 if (pos() == lastpos() && inset().idxDelete(idx()))
649 // special behaviour when in last position of cell
650 if (pos() == lastpos()) {
651 bool one_cell = inset().nargs() == 1;
652 if (one_cell && depth() == 1 && lastpos() == 0)
658 inset().idxGlue(idx());
662 // 'clever' UI hack: only erase large items if previously slected
663 if (pos() != lastpos() && inset().nargs() > 0) {
678 DocIterator save = *this;
681 setCursor(save, false);
682 autocorrect() = false;
690 DocIterator save = *this;
693 setCursor(save, false);
694 autocorrect() = false;
699 void LCursor::macroModeClose()
703 MathUnknownInset * p = activeMacro();
705 string s = p->name();
709 // do nothing if the macro name is empty
713 string const name = s.substr(1);
715 // prevent entering of recursive macros
716 // FIXME: this is only a weak attempt... only prevents immediate
718 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
719 if (macro && macro->getInsetName() == name)
720 lyxerr << "can't enter recursive macro" << endl;
722 //niceInsert(createMathInset(name));
723 plainInsert(createMathInset(name));
727 string LCursor::macroName()
729 return inMacroMode() ? activeMacro()->name() : string();
733 void LCursor::handleNest(MathAtom const & a, int c)
735 //lyxerr << "LCursor::handleNest: " << c << endl;
737 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
740 pushLeft(*nextInset());
744 int LCursor::targetX() const
746 if (x_target() != -1)
755 bool LCursor::inMacroMode() const
759 MathUnknownInset const * p = prevAtom()->asUnknownInset();
760 return p && !p->final();
764 MathUnknownInset * LCursor::activeMacro()
766 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
770 void LCursor::pullArg()
775 MathArray ar = cell();
776 if (popLeft() && inMathed()) {
778 cell().insert(pos(), ar);
781 //formula()->mutateToText();
786 void LCursor::touch()
792 DocIterator::const_iterator it = begin();
793 DocIterator::const_iterator et = end();
794 for ( ; it != et; ++it)
800 void LCursor::normalize()
802 if (idx() >= nargs()) {
803 lyxerr << "this should not really happen - 1: "
804 << idx() << ' ' << nargs()
805 << " in: " << &inset() << endl;
807 idx() = min(idx(), lastidx());
809 if (pos() > lastpos()) {
810 lyxerr << "this should not really happen - 2: "
811 << pos() << ' ' << lastpos() << " in idx: " << idx()
813 WriteStream wi(lyxerr, false, true);
814 inset().asMathInset()->write(wi);
817 pos() = min(pos(), lastpos());
821 bool LCursor::goUpDown(bool up)
823 // Be warned: The 'logic' implemented in this function is highly
824 // fragile. A distance of one pixel or a '<' vs '<=' _really
825 // matters. So fiddle around with it only if you think you know
826 // what you are doing!
832 // check if we had something else in mind, if not, this is the future goal
833 if (x_target() == -1)
838 // try neigbouring script insets
842 MathScriptInset const * p = prevAtom()->asScriptInset();
843 if (p && p->has(up)) {
846 idx() = up; // the superscript has index 1
848 //lyxerr << "updown: handled by scriptinset to the left" << endl;
854 if (pos() != lastpos()) {
855 MathScriptInset const * p = nextAtom()->asScriptInset();
856 if (p && p->has(up)) {
860 //lyxerr << "updown: handled by scriptinset to the right" << endl;
866 // try current cell for e.g. text insets
867 if (inset().idxUpDown2(*this, up))
870 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
875 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
876 // lyxerr << "updown: handled by brute find in the same cell" << endl;
880 // try to find an inset that knows better then we
882 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
884 if (inset().idxUpDown(*this, up)) {
885 // try to find best position within this inset
891 // no such inset found, just take something "above"
892 //lyxerr << "updown: handled by strange case" << endl;
894 int ylow = up ? 0 : yo + 1;
895 int yhigh = up ? yo - 1 : bv().workHeight();
896 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
899 // any improvement so far?
902 if (up ? ynew < yo : ynew > yo)
908 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
910 BOOST_ASSERT(!empty());
912 CursorSlice bottom = operator[](0);
913 LyXText * text = bottom.text();
915 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
917 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
918 DocIterator et = doc_iterator_end(bv().buffer()->inset());
919 //lyxerr << "x: " << x << " y: " << y << endl;
920 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
921 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
924 //et.par() = text->parOffset(end);
926 double best_dist = 10e10;
927 DocIterator best_cursor = it;
929 for ( ; it != et; it.forwardPos()) {
930 // avoid invalid nesting when selecting
931 if (!selection() || positionable(it, anchor_)) {
934 cur.setCursor(it, false);
935 cur.inset().getCursorPos(cur, xo, yo);
936 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
937 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
938 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
939 // '<=' in order to take the last possible position
940 // this is important for clicking behind \sum in e.g. '\sum_i a'
941 if (d <= best_dist) {
942 //lyxerr << "*" << endl;
950 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
951 if (best_dist < 1e10)
952 setCursor(best_cursor, false);
953 return best_dist < 1e10;
957 void LCursor::bruteFind2(int x, int y)
959 double best_dist = 1e10;
961 DocIterator it = *this;
963 DocIterator et = *this;
964 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
965 for (int i = 0; ; ++i) {
968 cur.setCursor(it, false);
969 cur.inset().getCursorPos(cur, xo, yo);
970 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
971 // '<=' in order to take the last possible position
972 // this is important for clicking behind \sum in e.g. '\sum_i a'
973 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
974 if (d <= best_dist) {
976 setCursor(it, false);
985 void LCursor::handleFont(string const & font)
987 lyxerr << "LCursor::handleFont: " << font << endl;
991 safe = lyx::cap::grabAndEraseSelection(*this);
994 if (lastpos() != 0) {
995 // something left in the cell
997 // cursor in first position
999 } else if (pos() == lastpos()) {
1000 // cursor in last position
1003 // cursor in between. split cell
1004 MathArray::iterator bt = cell().begin();
1005 MathAtom at = createMathInset(font);
1006 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1007 cell().erase(bt, bt + pos());
1012 // nothing left in the cell
1020 void LCursor::message(string const & msg) const
1022 bv().owner()->getLyXFunc().setMessage(msg);
1026 void LCursor::errorMessage(string const & msg) const
1028 bv().owner()->getLyXFunc().setErrorMessage(msg);
1032 string LCursor::selectionAsString(bool label) const
1038 Buffer const & buffer = *bv().buffer();
1039 ParagraphList & pars = text()->paragraphs();
1041 // should be const ...
1042 par_type startpit = selBegin().par();
1043 par_type endpit = selEnd().par();
1044 size_t const startpos = selBegin().pos();
1045 size_t const endpos = selEnd().pos();
1047 if (startpit == endpit)
1048 return pars[startpit].asString(buffer, startpos, endpos, label);
1050 // First paragraph in selection
1051 string result = pars[startpit].
1052 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1054 // The paragraphs in between (if any)
1055 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1056 Paragraph & par = pars[pit];
1057 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1060 // Last paragraph in selection
1061 result += pars[endpit].asString(buffer, 0, endpos, label);
1066 #ifdef WITH_WARNINGS
1067 #warning and mathed?
1073 string LCursor::currentState()
1076 std::ostringstream os;
1082 return text()->currentState(*this);
1088 string LCursor::getPossibleLabel()
1090 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1094 Encoding const * LCursor::getEncoding() const
1101 // go up until first non-0 text is hit
1102 // (innermost text is 0 in mathed)
1103 for (s = size() - 1; s >= 0; --s)
1104 if (operator[](s).text())
1106 CursorSlice const & sl = operator[](s);
1107 LyXText & text = *sl.text();
1108 LyXFont font = text.getPar(sl.par()).getFont(
1109 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1110 return font.language()->encoding();
1114 void LCursor::undispatched()
1116 disp_.dispatched(false);
1120 void LCursor::dispatched()
1122 disp_.dispatched(true);
1126 void LCursor::noUpdate()
1128 disp_.update(false);