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/updatableinset.h"
36 #include "insets/insettabular.h"
37 #include "insets/insettext.h"
39 #include "mathed/math_data.h"
40 #include "mathed/math_inset.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) {
102 cur.inset().getCursorPos(cur.top(), xo, yo);
103 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
104 // '<=' in order to take the last possible position
105 // this is important for clicking behind \sum in e.g. '\sum_i a'
106 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
107 << " best: " << best_dist << endl;
108 if (d <= best_dist) {
120 /// moves position closest to (x, y) in given box
121 bool bruteFind(LCursor & cursor,
122 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
124 BOOST_ASSERT(!cursor.empty());
125 CursorSlice bottom = cursor[0];
127 DocIterator it = doc_iterator_begin(bottom.inset());
128 DocIterator const et = doc_iterator_end(bottom.inset());
130 double best_dist = std::numeric_limits<double>::max();;
131 DocIterator best_cursor = et;
133 for ( ; it != et; it.forwardPos()) {
134 // avoid invalid nesting when selecting
135 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
136 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
137 Point p = bv_funcs::getPos(it);
140 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
141 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
142 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
143 // '<=' in order to take the last possible position
144 // this is important for clicking behind \sum in e.g. '\sum_i a'
145 if (d <= best_dist) {
146 //lyxerr << "*" << endl;
154 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
155 if (best_cursor != et) {
156 cursor.setCursor(best_cursor);
166 // be careful: this is called from the bv's constructor, too, so
167 // bv functions are not yet available!
168 LCursor::LCursor(BufferView & bv)
169 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
170 selection_(false), mark_(false)
174 void LCursor::reset(InsetBase & inset)
177 push_back(CursorSlice(inset));
178 anchor_ = DocIterator(inset);
185 // this (intentionally) does neither touch anchor nor selection status
186 void LCursor::setCursor(DocIterator const & cur)
188 DocIterator::operator=(cur);
192 void LCursor::dispatch(FuncRequest const & cmd0)
194 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
195 << " cmd: " << cmd0 << '\n'
201 FuncRequest cmd = cmd0;
202 LCursor safe = *this;
204 for (; depth(); pop()) {
205 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
206 << cmd0 << endl << *this << endl;
207 BOOST_ASSERT(pos() <= lastpos());
208 BOOST_ASSERT(idx() <= lastidx());
209 BOOST_ASSERT(pit() <= lastpit());
211 // The common case is 'LFUN handled, need update', so make the
212 // LFUN handler's life easier by assuming this as default value.
213 // The handler can reset the update and val flags if necessary.
215 disp_.dispatched(true);
216 inset().dispatch(*this, cmd);
217 if (disp_.dispatched())
220 // it completely to get a 'bomb early' behaviour in case this
221 // object will be used again.
222 if (!disp_.dispatched()) {
223 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
225 disp_.dispatched(false);
230 DispatchResult LCursor::result() const
236 BufferView & LCursor::bv() const
243 Buffer & LCursor::buffer() const
246 BOOST_ASSERT(bv_->buffer());
247 return *bv_->buffer();
253 BOOST_ASSERT(depth() >= 1);
258 void LCursor::push(InsetBase & p)
260 push_back(CursorSlice(p));
264 void LCursor::pushLeft(InsetBase & p)
266 BOOST_ASSERT(!empty());
267 //lyxerr << "Entering inset " << t << " left" << endl;
273 bool LCursor::popLeft()
275 BOOST_ASSERT(!empty());
276 //lyxerr << "Leaving inset to the left" << endl;
277 inset().notifyCursorLeaves(*this);
285 bool LCursor::popRight()
287 BOOST_ASSERT(!empty());
288 //lyxerr << "Leaving inset to the right" << endl;
289 inset().notifyCursorLeaves(*this);
298 int LCursor::currentMode()
300 BOOST_ASSERT(!empty());
301 for (int i = depth() - 1; i >= 0; --i) {
302 int res = operator[](i).inset().currentMode();
303 if (res != InsetBase::UNDECIDED_MODE)
306 return InsetBase::TEXT_MODE;
310 void LCursor::getPos(int & x, int & y) const
312 Point p = bv_funcs::getPos(*this);
318 void LCursor::paste(string const & data)
320 dispatch(FuncRequest(LFUN_PASTE, data));
324 void LCursor::resetAnchor()
331 bool LCursor::posLeft()
340 bool LCursor::posRight()
342 if (pos() == lastpos())
349 CursorSlice LCursor::anchor() const
351 BOOST_ASSERT(anchor_.depth() >= depth());
352 CursorSlice normal = anchor_[depth() - 1];
353 if (depth() < anchor_.depth() && top() <= normal) {
354 // anchor is behind cursor -> move anchor behind the inset
361 CursorSlice LCursor::selBegin() const
365 return anchor() < top() ? anchor() : top();
369 CursorSlice LCursor::selEnd() const
373 return anchor() > top() ? anchor() : top();
377 DocIterator LCursor::selectionBegin() const
381 return anchor() < top() ? anchor_ : *this;
385 DocIterator LCursor::selectionEnd() const
389 return anchor() > top() ? anchor_ : *this;
393 void LCursor::setSelection()
396 // a selection with no contents is not a selection
398 #warning doesnt look ok
400 if (pit() == anchor().pit() && pos() == anchor().pos())
405 void LCursor::setSelection(DocIterator const & where, size_t n)
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 (unsigned i = 0; i < depth(); ++i)
511 if (&operator[](i).inset() == p)
517 bool LCursor::openable(MathAtom const & t) const
528 // we can't move into anything new during selection
529 if (depth() >= anchor_.depth())
531 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
538 void LCursor::setScreenPos(int x, int y)
541 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
546 void LCursor::plainErase()
552 void LCursor::markInsert()
558 void LCursor::markErase()
564 void LCursor::plainInsert(MathAtom const & t)
566 cell().insert(pos(), t);
571 void LCursor::insert(string const & str)
573 for_each(str.begin(), str.end(),
574 boost::bind(static_cast<void(LCursor::*)(char)>
575 (&LCursor::insert), this, _1));
579 void LCursor::insert(char c)
581 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
582 BOOST_ASSERT(!empty());
584 lyx::cap::selClearOrDel(*this);
585 insert(new MathCharInset(c));
587 text()->insertChar(*this, c);
592 void LCursor::insert(MathAtom const & t)
594 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
596 lyx::cap::selClearOrDel(*this);
601 void LCursor::insert(InsetBase * inset)
604 insert(MathAtom(inset));
606 text()->insertInset(*this, inset);
610 void LCursor::niceInsert(string const & t)
621 void LCursor::niceInsert(MathAtom const & t)
624 string const safe = lyx::cap::grabAndEraseSelection(*this);
626 // enter the new inset and move the contents of the selection if possible
629 // be careful here: don't use 'pushLeft(t)' as this we need to
630 // push the clone, not the original
631 pushLeft(*nextInset());
637 void LCursor::insert(MathArray const & ar)
641 lyx::cap::eraseSelection(*this);
642 cell().insert(pos(), ar);
647 bool LCursor::backspace()
649 autocorrect() = false;
652 lyx::cap::selDel(*this);
657 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
664 MathUnknownInset * p = activeMacro();
665 if (p->name().size() > 1) {
666 p->setName(p->name().substr(0, p->name().size() - 1));
671 if (pos() != 0 && prevAtom()->nargs() > 0) {
672 // let's require two backspaces for 'big stuff' and
673 // highlight on the first
685 bool LCursor::erase()
687 autocorrect() = false;
692 lyx::cap::selDel(*this);
696 // delete empty cells if possible
697 if (pos() == lastpos() && inset().idxDelete(idx()))
700 // special behaviour when in last position of cell
701 if (pos() == lastpos()) {
702 bool one_cell = inset().nargs() == 1;
703 if (one_cell && depth() == 1 && lastpos() == 0)
709 inset().idxGlue(idx());
713 // 'clever' UI hack: only erase large items if previously slected
714 if (pos() != lastpos() && inset().nargs() > 0) {
729 DocIterator save = *this;
733 autocorrect() = false;
741 DocIterator save = *this;
745 autocorrect() = false;
750 void LCursor::macroModeClose()
754 MathUnknownInset * p = activeMacro();
756 string const s = p->name();
760 // do nothing if the macro name is empty
764 string const name = s.substr(1);
766 // prevent entering of recursive macros
767 // FIXME: this is only a weak attempt... only prevents immediate
769 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
770 if (macro && macro->getInsetName() == name)
771 lyxerr << "can't enter recursive macro" << endl;
773 plainInsert(createMathInset(name));
777 string LCursor::macroName()
779 return inMacroMode() ? activeMacro()->name() : string();
783 void LCursor::handleNest(MathAtom const & a, int c)
785 //lyxerr << "LCursor::handleNest: " << c << endl;
787 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
790 pushLeft(*nextInset());
794 int LCursor::targetX() const
796 if (x_target() != -1)
805 void LCursor::setTargetX()
807 // For now this is good enough. A better solution would be to
808 // avoid this rebreak by setting cursorX only after drawing
809 bottom().text()->redoParagraph(bottom().pit());
817 bool LCursor::inMacroMode() const
821 MathUnknownInset const * p = prevAtom()->asUnknownInset();
822 return p && !p->final();
826 MathUnknownInset * LCursor::activeMacro()
828 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
832 void LCursor::pullArg()
837 MathArray ar = cell();
838 if (popLeft() && inMathed()) {
840 cell().insert(pos(), ar);
843 //formula()->mutateToText();
848 void LCursor::touch()
854 DocIterator::const_iterator it = begin();
855 DocIterator::const_iterator et = end();
856 for ( ; it != et; ++it)
862 void LCursor::normalize()
864 if (idx() >= nargs()) {
865 lyxerr << "this should not really happen - 1: "
866 << idx() << ' ' << nargs()
867 << " in: " << &inset() << endl;
869 idx() = min(idx(), lastidx());
871 if (pos() > lastpos()) {
872 lyxerr << "this should not really happen - 2: "
873 << pos() << ' ' << lastpos() << " in idx: " << idx()
875 WriteStream wi(lyxerr, false, true);
876 inset().asMathInset()->write(wi);
879 pos() = min(pos(), lastpos());
883 bool LCursor::goUpDown(bool up)
885 // Be warned: The 'logic' implemented in this function is highly
886 // fragile. A distance of one pixel or a '<' vs '<=' _really
887 // matters. So fiddle around with it only if you think you know
888 // what you are doing!
894 // check if we had something else in mind, if not, this is the future goal
895 if (x_target() == -1)
900 // try neigbouring script insets
904 MathScriptInset const * p = prevAtom()->asScriptInset();
905 if (p && p->has(up)) {
908 idx() = up; // the superscript has index 1
910 //lyxerr << "updown: handled by scriptinset to the left" << endl;
916 if (pos() != lastpos()) {
917 MathScriptInset const * p = nextAtom()->asScriptInset();
918 if (p && p->has(up)) {
922 //lyxerr << "updown: handled by scriptinset to the right" << endl;
928 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
933 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
934 // lyxerr << "updown: handled by brute find in the same cell" << endl;
938 // try to find an inset that knows better then we
940 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
942 if (inset().idxUpDown(*this, up)) {
943 // try to find best position within this inset
945 setCursor(bruteFind2(*this, xo, yo));
949 // no such inset found, just take something "above"
950 //lyxerr << "updown: handled by strange case" << endl;
952 int ylow = up ? 0 : yo + 1;
953 int yhigh = up ? yo - 1 : bv().workHeight();
954 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
957 // any improvement so far?
961 if (up ? ynew < yo : ynew > yo)
965 // we should not come here.
970 void LCursor::handleFont(string const & font)
972 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
976 safe = lyx::cap::grabAndEraseSelection(*this);
979 if (lastpos() != 0) {
980 // something left in the cell
982 // cursor in first position
984 } else if (pos() == lastpos()) {
985 // cursor in last position
988 // cursor in between. split cell
989 MathArray::iterator bt = cell().begin();
990 MathAtom at = createMathInset(font);
991 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
992 cell().erase(bt, bt + pos());
997 // nothing left in the cell
1005 void LCursor::message(string const & msg) const
1007 bv().owner()->getLyXFunc().setMessage(msg);
1011 void LCursor::errorMessage(string const & msg) const
1013 bv().owner()->getLyXFunc().setErrorMessage(msg);
1017 string LCursor::selectionAsString(bool label) const
1023 Buffer const & buffer = *bv().buffer();
1024 ParagraphList & pars = text()->paragraphs();
1026 // should be const ...
1027 pit_type startpit = selBegin().pit();
1028 pit_type endpit = selEnd().pit();
1029 size_t const startpos = selBegin().pos();
1030 size_t const endpos = selEnd().pos();
1032 if (startpit == endpit)
1033 return pars[startpit].asString(buffer, startpos, endpos, label);
1035 // First paragraph in selection
1036 string result = pars[startpit].
1037 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1039 // The paragraphs in between (if any)
1040 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1041 Paragraph & par = pars[pit];
1042 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1045 // Last paragraph in selection
1046 result += pars[endpit].asString(buffer, 0, endpos, label);
1051 #ifdef WITH_WARNINGS
1052 #warning and mathed?
1058 string LCursor::currentState()
1061 std::ostringstream os;
1067 return text()->currentState(*this);
1073 string LCursor::getPossibleLabel()
1075 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1079 Encoding const * LCursor::getEncoding() const
1086 // go up until first non-0 text is hit
1087 // (innermost text is 0 in mathed)
1088 for (s = depth() - 1; s >= 0; --s)
1089 if (operator[](s).text())
1091 CursorSlice const & sl = operator[](s);
1092 LyXText const & text = *sl.text();
1093 LyXFont font = text.getPar(sl.pit()).getFont(
1094 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1095 return font.language()->encoding();
1099 void LCursor::undispatched()
1101 disp_.dispatched(false);
1105 void LCursor::dispatched()
1107 disp_.dispatched(true);
1111 void LCursor::needsUpdate()
1117 void LCursor::noUpdate()
1119 disp_.update(false);
1123 LyXFont LCursor::getFont() const
1125 // HACK. far from being perfect...
1127 // go up until first non-0 text is hit
1128 // (innermost text is 0 in mathed)
1129 for (s = depth() - 1; s >= 0; --s)
1130 if (operator[](s).text())
1132 CursorSlice const & sl = operator[](s);
1133 LyXText const & text = *sl.text();
1134 LyXFont font = text.getPar(sl.pit()).getFont(
1135 bv().buffer()->params(),
1137 outerFont(sl.pit(), text.paragraphs()));
1143 void LCursor::fixIfBroken()
1145 // find out last good level
1146 LCursor copy = *this;
1147 size_t newdepth = depth();
1148 while (!copy.empty()) {
1149 if (copy.idx() > copy.lastidx()) {
1150 lyxerr << "wrong idx " << copy.idx()
1151 << ", max is " << copy.lastidx()
1152 << " at level " << copy.depth()
1153 << ". Trying to correct this." << endl;
1154 newdepth = copy.depth() - 1;
1156 else if (copy.pit() > copy.lastpit()) {
1157 lyxerr << "wrong pit " << copy.pit()
1158 << ", max is " << copy.lastpit()
1159 << " at level " << copy.depth()
1160 << ". Trying to correct this." << endl;
1161 newdepth = copy.depth() - 1;
1163 else if (copy.pos() > copy.lastpos()) {
1164 lyxerr << "wrong pos " << copy.pos()
1165 << ", max is " << copy.lastpos()
1166 << " at level " << copy.depth()
1167 << ". Trying to correct this." << endl;
1168 newdepth = copy.depth() - 1;
1172 // shrink cursor to a size where everything is valid, possibly
1174 while (depth() > newdepth) {
1176 lyxerr << "correcting cursor to level " << depth() << endl;