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_scriptinset.h"
41 #include "mathed/math_macrotable.h"
43 #include "support/limited_stack.h"
45 #include "frontends/LyXView.h"
46 #include "frontends/font_metrics.h"
48 #include <boost/assert.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/current_function.hpp>
60 #ifndef CXX_GLOBAL_CSTD
69 positionable(DocIterator const & cursor, DocIterator const & anchor)
71 // avoid deeper nested insets when selecting
72 if (cursor.depth() > anchor.depth())
75 // anchor might be deeper, should have same path then
76 for (size_t i = 0; i < cursor.depth(); ++i)
77 if (&cursor[i].inset() != &anchor[i].inset())
80 // position should be ok.
85 // Find position closest to (x, y) in cell given by iter.
86 // Used only in mathed
87 DocIterator bruteFind2(LCursor const & c, int x, int y)
89 double best_dist = std::numeric_limits<double>::max();
96 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
97 for (int i = 0; ; ++i) {
100 it.inset().cursorPos(it.top(), c.boundary() && ((i+1) == it.depth()), xo, yo);
101 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
102 // '<=' in order to take the last possible position
103 // this is important for clicking behind \sum in e.g. '\sum_i a'
104 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
105 << " best: " << best_dist << endl;
106 if (d <= best_dist) {
118 /// moves position closest to (x, y) in given box
119 bool bruteFind(LCursor & cursor,
120 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
122 BOOST_ASSERT(!cursor.empty());
123 CursorSlice bottom = cursor[0];
125 DocIterator it = doc_iterator_begin(bottom.inset());
126 DocIterator const et = doc_iterator_end(bottom.inset());
128 double best_dist = std::numeric_limits<double>::max();;
129 DocIterator best_cursor = et;
131 for ( ; it != et; it.forwardPos()) {
132 // avoid invalid nesting when selecting
133 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
134 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
135 Point p = bv_funcs::getPos(it, false);
138 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
139 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
140 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
141 // '<=' in order to take the last possible position
142 // this is important for clicking behind \sum in e.g. '\sum_i a'
143 if (d <= best_dist) {
144 //lyxerr << "*" << endl;
152 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
153 if (best_cursor != et) {
154 cursor.setCursor(best_cursor);
164 // be careful: this is called from the bv's constructor, too, so
165 // bv functions are not yet available!
166 LCursor::LCursor(BufferView & bv)
167 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
168 selection_(false), mark_(false), logicalpos_(false)
172 void LCursor::reset(InsetBase & inset)
175 push_back(CursorSlice(inset));
176 anchor_ = DocIterator(inset);
183 // this (intentionally) does neither touch anchor nor selection status
184 void LCursor::setCursor(DocIterator const & cur)
186 DocIterator::operator=(cur);
190 void LCursor::dispatch(FuncRequest const & cmd0)
192 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
193 << " cmd: " << cmd0 << '\n'
199 FuncRequest cmd = cmd0;
200 LCursor safe = *this;
202 for (; depth(); pop()) {
203 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
204 << cmd0 << endl << *this << endl;
205 BOOST_ASSERT(pos() <= lastpos());
206 BOOST_ASSERT(idx() <= lastidx());
207 BOOST_ASSERT(pit() <= lastpit());
209 // The common case is 'LFUN handled, need update', so make the
210 // LFUN handler's life easier by assuming this as default value.
211 // The handler can reset the update and val flags if necessary.
213 disp_.dispatched(true);
214 inset().dispatch(*this, cmd);
215 if (disp_.dispatched())
218 // it completely to get a 'bomb early' behaviour in case this
219 // object will be used again.
220 if (!disp_.dispatched()) {
221 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
223 disp_.dispatched(false);
228 DispatchResult LCursor::result() const
234 BufferView & LCursor::bv() const
241 Buffer & LCursor::buffer() const
244 BOOST_ASSERT(bv_->buffer());
245 return *bv_->buffer();
251 BOOST_ASSERT(depth() >= 1);
256 void LCursor::push(InsetBase & p)
258 push_back(CursorSlice(p));
262 void LCursor::pushLeft(InsetBase & p)
264 BOOST_ASSERT(!empty());
265 //lyxerr << "Entering inset " << t << " left" << endl;
271 bool LCursor::popLeft()
273 BOOST_ASSERT(!empty());
274 //lyxerr << "Leaving inset to the left" << endl;
275 inset().notifyCursorLeaves(*this);
283 bool LCursor::popRight()
285 BOOST_ASSERT(!empty());
286 //lyxerr << "Leaving inset to the right" << endl;
287 inset().notifyCursorLeaves(*this);
296 int LCursor::currentMode()
298 BOOST_ASSERT(!empty());
299 for (int i = depth() - 1; i >= 0; --i) {
300 int res = operator[](i).inset().currentMode();
301 if (res != InsetBase::UNDECIDED_MODE)
304 return InsetBase::TEXT_MODE;
308 void LCursor::getPos(int & x, int & y) const
310 Point p = bv_funcs::getPos(*this, boundary());
316 void LCursor::paste(string const & data)
318 dispatch(FuncRequest(LFUN_PASTE, data));
322 void LCursor::resetAnchor()
329 bool LCursor::posLeft()
338 bool LCursor::posRight()
340 if (pos() == lastpos())
347 CursorSlice LCursor::anchor() const
349 BOOST_ASSERT(anchor_.depth() >= depth());
350 CursorSlice normal = anchor_[depth() - 1];
351 if (depth() < anchor_.depth() && top() <= normal) {
352 // anchor is behind cursor -> move anchor behind the inset
359 CursorSlice LCursor::selBegin() const
363 return anchor() < top() ? anchor() : top();
367 CursorSlice LCursor::selEnd() const
371 return anchor() > top() ? anchor() : top();
375 DocIterator LCursor::selectionBegin() const
379 return anchor() < top() ? anchor_ : *this;
383 DocIterator LCursor::selectionEnd() const
387 return anchor() > top() ? anchor_ : *this;
391 void LCursor::setSelection()
394 // A selection with no contents is not a selection
396 #warning doesnt look ok
398 if (pit() == anchor().pit() && pos() == anchor().pos())
403 void LCursor::setSelection(DocIterator const & where, size_t n)
409 // Open all collapsed insets
410 for (int i = depth() - 1; i >= 0; --i)
411 operator[](i).inset().setStatus(*this, InsetBase::Open);
415 void LCursor::clearSelection()
424 int & LCursor::x_target()
430 int LCursor::x_target() const
436 void LCursor::clearTargetX()
443 void LCursor::info(std::ostream & os) const
445 for (int i = 1, n = depth(); i < n; ++i) {
446 operator[](i).inset().infoize(os);
450 prevInset()->infoize2(os);
451 // overwite old message
456 void LCursor::selHandle(bool sel)
458 //lyxerr << "LCursor::selHandle" << endl;
459 if (sel == selection())
467 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
469 os << "\n cursor: | anchor:\n";
470 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
471 os << " " << cur[i] << " | ";
472 if (i < cur.anchor_.depth())
473 os << cur.anchor_[i];
475 os << "-------------------------------";
478 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
479 os << "------------------------------- | " << cur.anchor_[i] << "\n";
481 os << " selection: " << cur.selection_
482 << " x_target: " << cur.x_target_ << endl;
489 ///////////////////////////////////////////////////////////////////
491 // The part below is the non-integrated rest of the original math
492 // cursor. This should be either generalized for texted or moved
493 // back to mathed (in most cases to MathNestInset).
495 ///////////////////////////////////////////////////////////////////
497 #include "mathed/math_charinset.h"
498 #include "mathed/math_factory.h"
499 #include "mathed/math_gridinset.h"
500 #include "mathed/math_macroarg.h"
501 #include "mathed/math_mathmlstream.h"
502 #include "mathed/math_scriptinset.h"
503 #include "mathed/math_support.h"
504 #include "mathed/math_unknowninset.h"
506 //#define FILEDEBUG 1
509 bool LCursor::isInside(InsetBase const * p)
511 for (size_t i = 0; i != depth(); ++i)
512 if (&operator[](i).inset() == p)
518 void LCursor::leaveInset(InsetBase const & inset)
520 for (size_t i = 0; i != depth(); ++i) {
521 if (&operator[](i).inset() == &inset) {
529 bool LCursor::openable(MathAtom const & t) const
540 // we can't move into anything new during selection
541 if (depth() >= anchor_.depth())
543 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
550 void LCursor::setScreenPos(int x, int y)
553 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
558 void LCursor::plainErase()
564 void LCursor::markInsert()
570 void LCursor::markErase()
576 void LCursor::plainInsert(MathAtom const & t)
578 cell().insert(pos(), t);
583 void LCursor::insert(string const & str)
585 for_each(str.begin(), str.end(),
586 boost::bind(static_cast<void(LCursor::*)(char)>
587 (&LCursor::insert), this, _1));
591 void LCursor::insert(char c)
593 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
594 BOOST_ASSERT(!empty());
596 lyx::cap::selClearOrDel(*this);
597 insert(new MathCharInset(c));
599 text()->insertChar(*this, c);
604 void LCursor::insert(MathAtom const & t)
606 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
608 lyx::cap::selClearOrDel(*this);
613 void LCursor::insert(InsetBase * inset)
616 insert(MathAtom(inset));
618 text()->insertInset(*this, inset);
622 void LCursor::niceInsert(string const & t)
633 void LCursor::niceInsert(MathAtom const & t)
636 string const safe = lyx::cap::grabAndEraseSelection(*this);
638 // enter the new inset and move the contents of the selection if possible
641 // be careful here: don't use 'pushLeft(t)' as this we need to
642 // push the clone, not the original
643 pushLeft(*nextInset());
649 void LCursor::insert(MathArray const & ar)
653 lyx::cap::eraseSelection(*this);
654 cell().insert(pos(), ar);
659 bool LCursor::backspace()
661 autocorrect() = false;
664 lyx::cap::selDel(*this);
669 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
676 MathUnknownInset * p = activeMacro();
677 if (p->name().size() > 1) {
678 p->setName(p->name().substr(0, p->name().size() - 1));
683 if (pos() != 0 && prevAtom()->nargs() > 0) {
684 // let's require two backspaces for 'big stuff' and
685 // highlight on the first
697 bool LCursor::erase()
699 autocorrect() = false;
704 lyx::cap::selDel(*this);
708 // delete empty cells if possible
709 if (pos() == lastpos() && inset().idxDelete(idx()))
712 // special behaviour when in last position of cell
713 if (pos() == lastpos()) {
714 bool one_cell = inset().nargs() == 1;
715 if (one_cell && depth() == 1 && lastpos() == 0)
721 inset().idxGlue(idx());
725 // 'clever' UI hack: only erase large items if previously slected
726 if (pos() != lastpos() && inset().nargs() > 0) {
741 DocIterator save = *this;
745 autocorrect() = false;
753 DocIterator save = *this;
757 autocorrect() = false;
762 void LCursor::macroModeClose()
766 MathUnknownInset * p = activeMacro();
768 string const s = p->name();
772 // do nothing if the macro name is empty
776 string const name = s.substr(1);
778 // prevent entering of recursive macros
779 // FIXME: this is only a weak attempt... only prevents immediate
781 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
782 if (macro && macro->getInsetName() == name)
783 lyxerr << "can't enter recursive macro" << endl;
785 plainInsert(createMathInset(name));
789 string LCursor::macroName()
791 return inMacroMode() ? activeMacro()->name() : string();
795 void LCursor::handleNest(MathAtom const & a, int c)
797 //lyxerr << "LCursor::handleNest: " << c << endl;
799 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
802 pushLeft(*nextInset());
806 int LCursor::targetX() const
808 if (x_target() != -1)
817 void LCursor::setTargetX()
819 // For now this is good enough. A better solution would be to
820 // avoid this rebreak by setting cursorX only after drawing
821 bottom().text()->redoParagraph(bottom().pit());
829 bool LCursor::inMacroMode() const
833 MathUnknownInset const * p = prevAtom()->asUnknownInset();
834 return p && !p->final();
838 MathUnknownInset * LCursor::activeMacro()
840 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
844 void LCursor::pullArg()
849 MathArray ar = cell();
850 if (popLeft() && inMathed()) {
852 cell().insert(pos(), ar);
855 //formula()->mutateToText();
860 void LCursor::touch()
866 DocIterator::const_iterator it = begin();
867 DocIterator::const_iterator et = end();
868 for ( ; it != et; ++it)
874 void LCursor::normalize()
876 if (idx() >= nargs()) {
877 lyxerr << "this should not really happen - 1: "
878 << idx() << ' ' << nargs()
879 << " in: " << &inset() << endl;
881 idx() = min(idx(), lastidx());
883 if (pos() > lastpos()) {
884 lyxerr << "this should not really happen - 2: "
885 << pos() << ' ' << lastpos() << " in idx: " << idx()
887 WriteStream wi(lyxerr, false, true);
888 inset().asMathInset()->write(wi);
891 pos() = min(pos(), lastpos());
895 bool LCursor::goUpDown(bool up)
897 // Be warned: The 'logic' implemented in this function is highly
898 // fragile. A distance of one pixel or a '<' vs '<=' _really
899 // matters. So fiddle around with it only if you think you know
900 // what you are doing!
906 // check if we had something else in mind, if not, this is the future goal
907 if (x_target() == -1)
912 // try neigbouring script insets
916 MathScriptInset const * p = prevAtom()->asScriptInset();
917 if (p && p->has(up)) {
919 push(*const_cast<MathScriptInset*>(p));
920 idx() = p->idxOfScript(up);
927 if (pos() != lastpos()) {
928 MathScriptInset const * p = nextAtom()->asScriptInset();
929 if (p && p->has(up)) {
930 push(*const_cast<MathScriptInset*>(p));
931 idx() = p->idxOfScript(up);
938 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
943 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
944 // lyxerr << "updown: handled by brute find in the same cell" << endl;
948 // try to find an inset that knows better then we
950 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
952 if (inset().idxUpDown(*this, up)) {
953 // try to find best position within this inset
955 setCursor(bruteFind2(*this, xo, yo));
959 // no such inset found, just take something "above"
960 //lyxerr << "updown: handled by strange case" << endl;
962 int ylow = up ? 0 : yo + 1;
963 int yhigh = up ? yo - 1 : bv().workHeight();
964 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
967 // any improvement so far?
971 if (up ? ynew < yo : ynew > yo)
975 // we should not come here.
980 void LCursor::handleFont(string const & font)
982 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
986 safe = lyx::cap::grabAndEraseSelection(*this);
989 if (lastpos() != 0) {
990 // something left in the cell
992 // cursor in first position
994 } else if (pos() == lastpos()) {
995 // cursor in last position
998 // cursor in between. split cell
999 MathArray::iterator bt = cell().begin();
1000 MathAtom at = createMathInset(font);
1001 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1002 cell().erase(bt, bt + pos());
1007 // nothing left in the cell
1015 void LCursor::message(string const & msg) const
1017 bv().owner()->getLyXFunc().setMessage(msg);
1021 void LCursor::errorMessage(string const & msg) const
1023 bv().owner()->getLyXFunc().setErrorMessage(msg);
1027 string LCursor::selectionAsString(bool label) const
1033 Buffer const & buffer = *bv().buffer();
1034 ParagraphList & pars = text()->paragraphs();
1036 // should be const ...
1037 pit_type startpit = selBegin().pit();
1038 pit_type endpit = selEnd().pit();
1039 size_t const startpos = selBegin().pos();
1040 size_t const endpos = selEnd().pos();
1042 if (startpit == endpit)
1043 return pars[startpit].asString(buffer, startpos, endpos, label);
1045 // First paragraph in selection
1046 string result = pars[startpit].
1047 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1049 // The paragraphs in between (if any)
1050 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1051 Paragraph & par = pars[pit];
1052 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1055 // Last paragraph in selection
1056 result += pars[endpit].asString(buffer, 0, endpos, label);
1061 #ifdef WITH_WARNINGS
1062 #warning and mathed?
1068 string LCursor::currentState()
1071 std::ostringstream os;
1077 return text()->currentState(*this);
1083 string LCursor::getPossibleLabel()
1085 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1089 Encoding const * LCursor::getEncoding() const
1096 // go up until first non-0 text is hit
1097 // (innermost text is 0 in mathed)
1098 for (s = depth() - 1; s >= 0; --s)
1099 if (operator[](s).text())
1101 CursorSlice const & sl = operator[](s);
1102 LyXText const & text = *sl.text();
1103 LyXFont font = text.getPar(sl.pit()).getFont(
1104 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1105 return font.language()->encoding();
1109 void LCursor::undispatched()
1111 disp_.dispatched(false);
1115 void LCursor::dispatched()
1117 disp_.dispatched(true);
1121 void LCursor::needsUpdate()
1127 void LCursor::noUpdate()
1129 disp_.update(false);
1133 LyXFont LCursor::getFont() const
1135 // HACK. far from being perfect...
1137 // go up until first non-0 text is hit
1138 // (innermost text is 0 in mathed)
1139 for (s = depth() - 1; s >= 0; --s)
1140 if (operator[](s).text())
1142 CursorSlice const & sl = operator[](s);
1143 LyXText const & text = *sl.text();
1144 LyXFont font = text.getPar(sl.pit()).getFont(
1145 bv().buffer()->params(),
1147 outerFont(sl.pit(), text.paragraphs()));
1153 void LCursor::fixIfBroken()
1155 // find out last good level
1156 LCursor copy = *this;
1157 size_t newdepth = depth();
1158 while (!copy.empty()) {
1159 if (copy.idx() > copy.lastidx()) {
1160 lyxerr << "wrong idx " << copy.idx()
1161 << ", max is " << copy.lastidx()
1162 << " at level " << copy.depth()
1163 << ". Trying to correct this." << endl;
1164 newdepth = copy.depth() - 1;
1166 else if (copy.pit() > copy.lastpit()) {
1167 lyxerr << "wrong pit " << copy.pit()
1168 << ", max is " << copy.lastpit()
1169 << " at level " << copy.depth()
1170 << ". Trying to correct this." << endl;
1171 newdepth = copy.depth() - 1;
1173 else if (copy.pos() > copy.lastpos()) {
1174 lyxerr << "wrong pos " << copy.pos()
1175 << ", max is " << copy.lastpos()
1176 << " at level " << copy.depth()
1177 << ". Trying to correct this." << endl;
1178 newdepth = copy.depth() - 1;
1182 // shrink cursor to a size where everything is valid, possibly
1184 while (depth() > newdepth) {
1186 lyxerr << "correcting cursor to level " << depth() << endl;