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 "coordcache.h"
19 #include "CutAndPaste.h"
21 #include "dispatchresult.h"
23 #include "funcrequest.h"
27 #include "lyxfunc.h" // only for setMessage()
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.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"
45 #include "frontends/font_metrics.h"
47 #include <boost/assert.hpp>
48 #include <boost/bind.hpp>
49 #include <boost/current_function.hpp>
59 #ifndef CXX_GLOBAL_CSTD
68 positionable(DocIterator const & cursor, DocIterator const & anchor)
70 // avoid deeper nested insets when selecting
71 if (cursor.depth() > anchor.depth())
74 // anchor might be deeper, should have same path then
75 for (size_t i = 0; i < cursor.depth(); ++i)
76 if (&cursor[i].inset() != &anchor[i].inset())
79 // position should be ok.
84 // Find position closest to (x, y) in cell given by iter.
85 // Used only in mathed
86 DocIterator bruteFind2(LCursor const & c, int x, int y)
88 double best_dist = std::numeric_limits<double>::max();
95 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
96 for (int i = 0; ; ++i) {
99 it.inset().cursorPos(it.top(), c.boundary() && ((i+1) == it.depth()), xo, yo);
100 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
101 // '<=' in order to take the last possible position
102 // this is important for clicking behind \sum in e.g. '\sum_i a'
103 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
104 << " best: " << best_dist << endl;
105 if (d <= best_dist) {
117 /// moves position closest to (x, y) in given box
118 bool bruteFind(LCursor & cursor,
119 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
121 BOOST_ASSERT(!cursor.empty());
122 CursorSlice bottom = cursor[0];
124 DocIterator it = doc_iterator_begin(bottom.inset());
125 DocIterator const et = doc_iterator_end(bottom.inset());
127 double best_dist = std::numeric_limits<double>::max();;
128 DocIterator best_cursor = et;
130 for ( ; it != et; it.forwardPos()) {
131 // avoid invalid nesting when selecting
132 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
133 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
134 Point p = bv_funcs::getPos(it, false);
137 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
138 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
139 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
140 // '<=' in order to take the last possible position
141 // this is important for clicking behind \sum in e.g. '\sum_i a'
142 if (d <= best_dist) {
143 //lyxerr << "*" << endl;
151 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
152 if (best_cursor != et) {
153 cursor.setCursor(best_cursor);
163 // be careful: this is called from the bv's constructor, too, so
164 // bv functions are not yet available!
165 LCursor::LCursor(BufferView & bv)
166 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
167 selection_(false), mark_(false), logicalpos_(false)
171 void LCursor::reset(InsetBase & inset)
174 push_back(CursorSlice(inset));
175 anchor_ = DocIterator(inset);
182 // this (intentionally) does neither touch anchor nor selection status
183 void LCursor::setCursor(DocIterator const & cur)
185 DocIterator::operator=(cur);
189 void LCursor::dispatch(FuncRequest const & cmd0)
191 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
192 << " cmd: " << cmd0 << '\n'
198 FuncRequest cmd = cmd0;
199 LCursor safe = *this;
201 for (; depth(); pop()) {
202 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
203 << cmd0 << endl << *this << endl;
204 BOOST_ASSERT(pos() <= lastpos());
205 BOOST_ASSERT(idx() <= lastidx());
206 BOOST_ASSERT(pit() <= lastpit());
208 // The common case is 'LFUN handled, need update', so make the
209 // LFUN handler's life easier by assuming this as default value.
210 // The handler can reset the update and val flags if necessary.
212 disp_.dispatched(true);
213 inset().dispatch(*this, cmd);
214 if (disp_.dispatched())
217 // it completely to get a 'bomb early' behaviour in case this
218 // object will be used again.
219 if (!disp_.dispatched()) {
220 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
222 disp_.dispatched(false);
227 DispatchResult LCursor::result() const
233 BufferView & LCursor::bv() const
240 Buffer & LCursor::buffer() const
243 BOOST_ASSERT(bv_->buffer());
244 return *bv_->buffer();
250 BOOST_ASSERT(depth() >= 1);
255 void LCursor::push(InsetBase & p)
257 push_back(CursorSlice(p));
261 void LCursor::pushLeft(InsetBase & p)
263 BOOST_ASSERT(!empty());
264 //lyxerr << "Entering inset " << t << " left" << endl;
270 bool LCursor::popLeft()
272 BOOST_ASSERT(!empty());
273 //lyxerr << "Leaving inset to the left" << endl;
274 inset().notifyCursorLeaves(*this);
282 bool LCursor::popRight()
284 BOOST_ASSERT(!empty());
285 //lyxerr << "Leaving inset to the right" << endl;
286 inset().notifyCursorLeaves(*this);
295 int LCursor::currentMode()
297 BOOST_ASSERT(!empty());
298 for (int i = depth() - 1; i >= 0; --i) {
299 int res = operator[](i).inset().currentMode();
300 if (res != InsetBase::UNDECIDED_MODE)
303 return InsetBase::TEXT_MODE;
307 void LCursor::getPos(int & x, int & y) const
309 Point p = bv_funcs::getPos(*this, boundary());
315 void LCursor::paste(string const & data)
317 dispatch(FuncRequest(LFUN_PASTE, data));
321 void LCursor::resetAnchor()
328 bool LCursor::posLeft()
337 bool LCursor::posRight()
339 if (pos() == lastpos())
346 CursorSlice LCursor::anchor() const
348 BOOST_ASSERT(anchor_.depth() >= depth());
349 CursorSlice normal = anchor_[depth() - 1];
350 if (depth() < anchor_.depth() && top() <= normal) {
351 // anchor is behind cursor -> move anchor behind the inset
358 CursorSlice LCursor::selBegin() const
362 return anchor() < top() ? anchor() : top();
366 CursorSlice LCursor::selEnd() const
370 return anchor() > top() ? anchor() : top();
374 DocIterator LCursor::selectionBegin() const
378 return anchor() < top() ? anchor_ : *this;
382 DocIterator LCursor::selectionEnd() const
386 return anchor() > top() ? anchor_ : *this;
390 void LCursor::setSelection()
393 // A selection with no contents is not a selection
395 #warning doesnt look ok
397 if (pit() == anchor().pit() && pos() == anchor().pos())
402 void LCursor::setSelection(DocIterator const & where, size_t n)
408 // Open all collapsed insets
409 for (int i = depth() - 1; i >= 0; --i)
410 operator[](i).inset().setStatus(*this, InsetBase::Open);
414 void LCursor::clearSelection()
423 int & LCursor::x_target()
429 int LCursor::x_target() const
435 void LCursor::clearTargetX()
442 void LCursor::info(std::ostream & os) const
444 for (int i = 1, n = depth(); i < n; ++i) {
445 operator[](i).inset().infoize(os);
449 prevInset()->infoize2(os);
450 // overwite old message
455 void LCursor::selHandle(bool sel)
457 //lyxerr << "LCursor::selHandle" << endl;
458 if (sel == selection())
466 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
468 os << "\n cursor: | anchor:\n";
469 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
470 os << " " << cur[i] << " | ";
471 if (i < cur.anchor_.depth())
472 os << cur.anchor_[i];
474 os << "-------------------------------";
477 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
478 os << "------------------------------- | " << cur.anchor_[i] << "\n";
480 os << " selection: " << cur.selection_
481 << " x_target: " << cur.x_target_ << endl;
488 ///////////////////////////////////////////////////////////////////
490 // The part below is the non-integrated rest of the original math
491 // cursor. This should be either generalized for texted or moved
492 // back to mathed (in most cases to MathNestInset).
494 ///////////////////////////////////////////////////////////////////
496 #include "mathed/math_charinset.h"
497 #include "mathed/math_factory.h"
498 #include "mathed/math_gridinset.h"
499 #include "mathed/math_macroarg.h"
500 #include "mathed/math_mathmlstream.h"
501 #include "mathed/math_scriptinset.h"
502 #include "mathed/math_support.h"
503 #include "mathed/math_unknowninset.h"
505 //#define FILEDEBUG 1
508 bool LCursor::isInside(InsetBase const * p)
510 for (size_t i = 0; i != depth(); ++i)
511 if (&operator[](i).inset() == p)
517 void LCursor::leaveInset(InsetBase const & inset)
519 for (size_t i = 0; i != depth(); ++i) {
520 if (&operator[](i).inset() == &inset) {
528 bool LCursor::openable(MathAtom const & t) const
539 // we can't move into anything new during selection
540 if (depth() >= anchor_.depth())
542 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
549 void LCursor::setScreenPos(int x, int y)
552 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
557 void LCursor::plainErase()
563 void LCursor::markInsert()
569 void LCursor::markErase()
575 void LCursor::plainInsert(MathAtom const & t)
577 cell().insert(pos(), t);
582 void LCursor::insert(string const & str)
584 for_each(str.begin(), str.end(),
585 boost::bind(static_cast<void(LCursor::*)(char)>
586 (&LCursor::insert), this, _1));
590 void LCursor::insert(char c)
592 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
593 BOOST_ASSERT(!empty());
595 lyx::cap::selClearOrDel(*this);
596 insert(new MathCharInset(c));
598 text()->insertChar(*this, c);
603 void LCursor::insert(MathAtom const & t)
605 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
607 lyx::cap::selClearOrDel(*this);
612 void LCursor::insert(InsetBase * inset)
615 insert(MathAtom(inset));
617 text()->insertInset(*this, inset);
621 void LCursor::niceInsert(string const & t)
632 void LCursor::niceInsert(MathAtom const & t)
635 string const safe = lyx::cap::grabAndEraseSelection(*this);
637 // enter the new inset and move the contents of the selection if possible
640 // be careful here: don't use 'pushLeft(t)' as this we need to
641 // push the clone, not the original
642 pushLeft(*nextInset());
648 void LCursor::insert(MathArray const & ar)
652 lyx::cap::eraseSelection(*this);
653 cell().insert(pos(), ar);
658 bool LCursor::backspace()
660 autocorrect() = false;
663 lyx::cap::selDel(*this);
668 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
675 MathUnknownInset * p = activeMacro();
676 if (p->name().size() > 1) {
677 p->setName(p->name().substr(0, p->name().size() - 1));
682 if (pos() != 0 && prevAtom()->nargs() > 0) {
683 // let's require two backspaces for 'big stuff' and
684 // highlight on the first
696 bool LCursor::erase()
698 autocorrect() = false;
703 lyx::cap::selDel(*this);
707 // delete empty cells if possible
708 if (pos() == lastpos() && inset().idxDelete(idx()))
711 // special behaviour when in last position of cell
712 if (pos() == lastpos()) {
713 bool one_cell = inset().nargs() == 1;
714 if (one_cell && depth() == 1 && lastpos() == 0)
720 inset().idxGlue(idx());
724 // 'clever' UI hack: only erase large items if previously slected
725 if (pos() != lastpos() && inset().nargs() > 0) {
740 DocIterator save = *this;
744 autocorrect() = false;
752 DocIterator save = *this;
756 autocorrect() = false;
761 void LCursor::macroModeClose()
765 MathUnknownInset * p = activeMacro();
767 string const s = p->name();
771 // do nothing if the macro name is empty
775 string const name = s.substr(1);
777 // prevent entering of recursive macros
778 // FIXME: this is only a weak attempt... only prevents immediate
780 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
781 if (macro && macro->getInsetName() == name)
782 lyxerr << "can't enter recursive macro" << endl;
784 plainInsert(createMathInset(name));
788 string LCursor::macroName()
790 return inMacroMode() ? activeMacro()->name() : string();
794 void LCursor::handleNest(MathAtom const & a, int c)
796 //lyxerr << "LCursor::handleNest: " << c << endl;
798 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
801 pushLeft(*nextInset());
805 int LCursor::targetX() const
807 if (x_target() != -1)
816 void LCursor::setTargetX()
818 // For now this is good enough. A better solution would be to
819 // avoid this rebreak by setting cursorX only after drawing
820 bottom().text()->redoParagraph(bottom().pit());
828 bool LCursor::inMacroMode() const
832 MathUnknownInset const * p = prevAtom()->asUnknownInset();
833 return p && !p->final();
837 MathUnknownInset * LCursor::activeMacro()
839 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
843 void LCursor::pullArg()
848 MathArray ar = cell();
849 if (popLeft() && inMathed()) {
851 cell().insert(pos(), ar);
854 //formula()->mutateToText();
859 void LCursor::touch()
865 DocIterator::const_iterator it = begin();
866 DocIterator::const_iterator et = end();
867 for ( ; it != et; ++it)
873 void LCursor::normalize()
875 if (idx() >= nargs()) {
876 lyxerr << "this should not really happen - 1: "
877 << idx() << ' ' << nargs()
878 << " in: " << &inset() << endl;
880 idx() = min(idx(), lastidx());
882 if (pos() > lastpos()) {
883 lyxerr << "this should not really happen - 2: "
884 << pos() << ' ' << lastpos() << " in idx: " << idx()
886 WriteStream wi(lyxerr, false, true);
887 inset().asMathInset()->write(wi);
890 pos() = min(pos(), lastpos());
894 bool LCursor::goUpDown(bool up)
896 // Be warned: The 'logic' implemented in this function is highly
897 // fragile. A distance of one pixel or a '<' vs '<=' _really
898 // matters. So fiddle around with it only if you think you know
899 // what you are doing!
905 // check if we had something else in mind, if not, this is the future goal
906 if (x_target() == -1)
911 // try neigbouring script insets
915 MathScriptInset const * p = prevAtom()->asScriptInset();
916 if (p && p->has(up)) {
919 idx() = up; // the superscript has index 1
921 //lyxerr << "updown: handled by scriptinset to the left" << endl;
927 if (pos() != lastpos()) {
928 MathScriptInset const * p = nextAtom()->asScriptInset();
929 if (p && p->has(up)) {
933 //lyxerr << "updown: handled by scriptinset to the right" << endl;
939 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
944 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
945 // lyxerr << "updown: handled by brute find in the same cell" << endl;
949 // try to find an inset that knows better then we
951 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
953 if (inset().idxUpDown(*this, up)) {
954 // try to find best position within this inset
956 setCursor(bruteFind2(*this, xo, yo));
960 // no such inset found, just take something "above"
961 //lyxerr << "updown: handled by strange case" << endl;
963 int ylow = up ? 0 : yo + 1;
964 int yhigh = up ? yo - 1 : bv().workHeight();
965 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
968 // any improvement so far?
972 if (up ? ynew < yo : ynew > yo)
976 // we should not come here.
981 void LCursor::handleFont(string const & font)
983 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << 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 pit_type startpit = selBegin().pit();
1039 pit_type endpit = selEnd().pit();
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 (pit_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 = depth() - 1; s >= 0; --s)
1100 if (operator[](s).text())
1102 CursorSlice const & sl = operator[](s);
1103 LyXText const & text = *sl.text();
1104 LyXFont font = text.getPar(sl.pit()).getFont(
1105 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), 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::needsUpdate()
1128 void LCursor::noUpdate()
1130 disp_.update(false);
1134 LyXFont LCursor::getFont() const
1136 // HACK. far from being perfect...
1138 // go up until first non-0 text is hit
1139 // (innermost text is 0 in mathed)
1140 for (s = depth() - 1; s >= 0; --s)
1141 if (operator[](s).text())
1143 CursorSlice const & sl = operator[](s);
1144 LyXText const & text = *sl.text();
1145 LyXFont font = text.getPar(sl.pit()).getFont(
1146 bv().buffer()->params(),
1148 outerFont(sl.pit(), text.paragraphs()));
1154 void LCursor::fixIfBroken()
1156 // find out last good level
1157 LCursor copy = *this;
1158 size_t newdepth = depth();
1159 while (!copy.empty()) {
1160 if (copy.idx() > copy.lastidx()) {
1161 lyxerr << "wrong idx " << copy.idx()
1162 << ", max is " << copy.lastidx()
1163 << " at level " << copy.depth()
1164 << ". Trying to correct this." << endl;
1165 newdepth = copy.depth() - 1;
1167 else if (copy.pit() > copy.lastpit()) {
1168 lyxerr << "wrong pit " << copy.pit()
1169 << ", max is " << copy.lastpit()
1170 << " at level " << copy.depth()
1171 << ". Trying to correct this." << endl;
1172 newdepth = copy.depth() - 1;
1174 else if (copy.pos() > copy.lastpos()) {
1175 lyxerr << "wrong pos " << copy.pos()
1176 << ", max is " << copy.lastpos()
1177 << " at level " << copy.depth()
1178 << ". Trying to correct this." << endl;
1179 newdepth = copy.depth() - 1;
1183 // shrink cursor to a size where everything is valid, possibly
1185 while (depth() > newdepth) {
1187 lyxerr << "correcting cursor to level " << depth() << endl;