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
329 #warning doesnt look ok
330 if (par() == anchor().par() && pos() == anchor().pos())
335 void LCursor::setSelection(DocIterator const & where, size_t n)
337 setCursor(where, true);
343 void LCursor::clearSelection()
352 int & LCursor::x_target()
358 int LCursor::x_target() const
364 void LCursor::clearTargetX()
371 void LCursor::info(std::ostream & os) const
373 for (int i = 1, n = depth(); i < n; ++i) {
374 operator[](i).inset().infoize(os);
378 prevInset()->infoize2(os);
379 // overwite old message
384 void LCursor::selHandle(bool sel)
386 //lyxerr << "LCursor::selHandle" << endl;
387 if (sel == selection()) {
388 #warning Alfredo: This is too strong (Andre)
399 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
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: " << endl;
545 lyx::cap::selClearOrDel(*this);
547 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
551 void LCursor::insert(InsetBase * inset)
554 insert(MathAtom(inset));
556 text()->insertInset(*this, inset);
560 void LCursor::niceInsert(string const & t)
571 void LCursor::niceInsert(MathAtom const & t)
574 string safe = lyx::cap::grabAndEraseSelection(*this);
576 // enter the new inset and move the contents of the selection if possible
579 // be careful here: don't use 'pushLeft(t)' as this we need to
580 // push the clone, not the original
581 pushLeft(*nextInset());
587 void LCursor::insert(MathArray const & ar)
591 lyx::cap::eraseSelection(*this);
592 cell().insert(pos(), ar);
597 bool LCursor::backspace()
599 autocorrect() = false;
602 lyx::cap::selDel(*this);
607 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
614 MathUnknownInset * p = activeMacro();
615 if (p->name().size() > 1) {
616 p->setName(p->name().substr(0, p->name().size() - 1));
621 if (pos() != 0 && prevAtom()->nargs() > 0) {
622 // let's require two backspaces for 'big stuff' and
623 // highlight on the first
635 bool LCursor::erase()
637 autocorrect() = false;
642 lyx::cap::selDel(*this);
646 // delete empty cells if possible
647 if (pos() == lastpos() && inset().idxDelete(idx()))
650 // special behaviour when in last position of cell
651 if (pos() == lastpos()) {
652 bool one_cell = inset().nargs() == 1;
653 if (one_cell && depth() == 1 && lastpos() == 0)
659 inset().idxGlue(idx());
663 // 'clever' UI hack: only erase large items if previously slected
664 if (pos() != lastpos() && inset().nargs() > 0) {
679 DocIterator save = *this;
682 setCursor(save, false);
683 autocorrect() = false;
691 DocIterator save = *this;
694 setCursor(save, false);
695 autocorrect() = false;
700 void LCursor::macroModeClose()
704 MathUnknownInset * p = activeMacro();
706 string s = p->name();
710 // do nothing if the macro name is empty
714 string const name = s.substr(1);
716 // prevent entering of recursive macros
717 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
718 if (macro && macro->getInsetName() == name)
719 lyxerr << "can't enter recursive macro" << endl;
721 niceInsert(createMathInset(name));
725 string LCursor::macroName()
727 return inMacroMode() ? activeMacro()->name() : string();
731 void LCursor::handleNest(MathAtom const & a, int c)
733 //lyxerr << "LCursor::handleNest: " << c << endl;
735 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
738 pushLeft(*nextInset());
742 int LCursor::targetX() const
744 if (x_target() != -1)
753 bool LCursor::inMacroMode() const
757 MathUnknownInset const * p = prevAtom()->asUnknownInset();
758 return p && !p->final();
762 MathUnknownInset * LCursor::activeMacro()
764 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
768 void LCursor::pullArg()
773 MathArray ar = cell();
774 if (popLeft() && inMathed()) {
776 cell().insert(pos(), ar);
779 //formula()->mutateToText();
784 void LCursor::touch()
790 DocIterator::const_iterator it = begin();
791 DocIterator::const_iterator et = end();
792 for ( ; it != et; ++it)
798 void LCursor::normalize()
800 if (idx() >= nargs()) {
801 lyxerr << "this should not really happen - 1: "
802 << idx() << ' ' << nargs()
803 << " in: " << &inset() << endl;
805 idx() = min(idx(), lastidx());
807 if (pos() > lastpos()) {
808 lyxerr << "this should not really happen - 2: "
809 << pos() << ' ' << lastpos() << " in idx: " << idx()
811 WriteStream wi(lyxerr, false, true);
812 inset().asMathInset()->write(wi);
815 pos() = min(pos(), lastpos());
819 bool LCursor::goUpDown(bool up)
821 // Be warned: The 'logic' implemented in this function is highly
822 // fragile. A distance of one pixel or a '<' vs '<=' _really
823 // matters. So fiddle around with it only if you think you know
824 // what you are doing!
830 // check if we had something else in mind, if not, this is the future goal
831 if (x_target() == -1)
836 // try neigbouring script insets
840 MathScriptInset const * p = prevAtom()->asScriptInset();
841 if (p && p->has(up)) {
844 idx() = up; // the superscript has index 1
846 //lyxerr << "updown: handled by scriptinset to the left" << endl;
852 if (pos() != lastpos()) {
853 MathScriptInset const * p = nextAtom()->asScriptInset();
854 if (p && p->has(up)) {
858 //lyxerr << "updown: handled by scriptinset to the right" << endl;
864 // try current cell for e.g. text insets
865 if (inset().idxUpDown2(*this, up))
868 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
873 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
874 // lyxerr << "updown: handled by brute find in the same cell" << endl;
878 // try to find an inset that knows better then we
880 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
882 if (inset().idxUpDown(*this, up)) {
883 // try to find best position within this inset
889 // no such inset found, just take something "above"
890 //lyxerr << "updown: handled by strange case" << endl;
892 int ylow = up ? 0 : yo + 1;
893 int yhigh = up ? yo - 1 : bv().workHeight();
894 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
897 // any improvement so far?
900 if (up ? ynew < yo : ynew > yo)
906 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
908 BOOST_ASSERT(!empty());
910 CursorSlice bottom = operator[](0);
911 LyXText * text = bottom.text();
913 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
915 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
916 DocIterator et = doc_iterator_end(bv().buffer()->inset());
917 //lyxerr << "x: " << x << " y: " << y << endl;
918 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
919 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
922 //et.par() = text->parOffset(end);
924 double best_dist = 10e10;
925 DocIterator best_cursor = it;
927 for ( ; it != et; it.forwardPos()) {
928 // avoid invalid nesting when selecting
929 if (!selection() || positionable(it, anchor_)) {
932 cur.setCursor(it, false);
933 cur.inset().getCursorPos(cur, xo, yo);
934 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
935 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
936 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
937 // '<=' in order to take the last possible position
938 // this is important for clicking behind \sum in e.g. '\sum_i a'
939 if (d <= best_dist) {
940 //lyxerr << "*" << endl;
948 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
949 if (best_dist < 1e10)
950 setCursor(best_cursor, false);
951 return best_dist < 1e10;
955 void LCursor::bruteFind2(int x, int y)
957 double best_dist = 1e10;
959 DocIterator it = *this;
961 DocIterator et = *this;
962 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
963 for (int i = 0; ; ++i) {
966 cur.setCursor(it, false);
967 cur.inset().getCursorPos(cur, xo, yo);
968 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
969 // '<=' in order to take the last possible position
970 // this is important for clicking behind \sum in e.g. '\sum_i a'
971 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
972 if (d <= best_dist) {
974 setCursor(it, false);
983 void LCursor::handleFont(string const & font)
985 lyxerr << "LCursor::handleFont: " << font << endl;
989 safe = lyx::cap::grabAndEraseSelection(*this);
992 if (lastpos() != 0) {
993 // something left in the cell
995 // cursor in first position
997 } else if (pos() == lastpos()) {
998 // cursor in last position
1001 // cursor in between. split cell
1002 MathArray::iterator bt = cell().begin();
1003 MathAtom at = createMathInset(font);
1004 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1005 cell().erase(bt, bt + pos());
1010 // nothing left in the cell
1018 void LCursor::message(string const & msg) const
1020 bv().owner()->getLyXFunc().setMessage(msg);
1024 void LCursor::errorMessage(string const & msg) const
1026 bv().owner()->getLyXFunc().setErrorMessage(msg);
1030 string LCursor::selectionAsString(bool label) const
1036 Buffer const & buffer = *bv().buffer();
1037 ParagraphList & pars = text()->paragraphs();
1039 // should be const ...
1040 par_type startpit = selBegin().par();
1041 par_type endpit = selEnd().par();
1042 size_t const startpos = selBegin().pos();
1043 size_t const endpos = selEnd().pos();
1045 if (startpit == endpit)
1046 return pars[startpit].asString(buffer, startpos, endpos, label);
1048 // First paragraph in selection
1049 string result = pars[startpit].
1050 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1052 // The paragraphs in between (if any)
1053 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1054 Paragraph & par = pars[pit];
1055 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1058 // Last paragraph in selection
1059 result += pars[endpit].asString(buffer, 0, endpos, label);
1064 #ifdef WITH_WARNINGS
1065 #warning and mathed?
1071 string LCursor::currentState()
1074 std::ostringstream os;
1080 return text()->currentState(*this);
1086 string LCursor::getPossibleLabel()
1088 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1092 Encoding const * LCursor::getEncoding() const
1099 // go up until first non-0 text is hit
1100 // (innermost text is 0 in mathed)
1101 for (s = size() - 1; s >= 0; --s)
1102 if (operator[](s).text())
1104 CursorSlice const & sl = operator[](s);
1105 LyXText & text = *sl.text();
1106 LyXFont font = text.getPar(sl.par()).getFont(
1107 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1108 return font.language()->encoding();
1112 void LCursor::undispatched()
1114 disp_.dispatched(false);
1118 void LCursor::dispatched()
1120 disp_.dispatched(true);
1124 void LCursor::noUpdate()
1126 disp_.update(false);