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>
59 #ifndef CXX_GLOBAL_CSTD
68 positionable(DocIterator const & cursor, DocIterator const & anchor)
70 // avoid deeper nested insets when selecting
71 if (cursor.size() > anchor.size())
74 // anchor might be deeper, should have same path then
75 for (size_t i = 0; i < cursor.size(); ++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.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
96 for (int i = 0; ; ++i) {
100 cur.inset().getCursorPos(cur.top(), 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];
124 LyXText * text = bottom.text();
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);
167 // be careful: this is called from the bv's constructor, too, so
168 // bv functions are not yet available!
169 LCursor::LCursor(BufferView & bv)
170 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
171 selection_(false), mark_(false)
175 void LCursor::reset(InsetBase & inset)
178 push_back(CursorSlice(inset));
179 anchor_ = DocIterator(inset);
186 // this (intentionally) does neither touch anchor nor selection status
187 void LCursor::setCursor(DocIterator const & cur)
189 DocIterator::operator=(cur);
193 void LCursor::dispatch(FuncRequest const & cmd0)
195 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
199 FuncRequest cmd = cmd0;
200 LCursor safe = *this;
202 for (; size(); pop()) {
203 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << 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 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
235 // This is, of course, a mess. Better create a new doc iterator and use
236 // this in Inset::getStatus. This might require an additional
237 // BufferView * arg, though (which should be avoided)
238 LCursor safe = *this;
240 for ( ; size(); pop()) {
241 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
242 if (idx() > lastidx()) {
243 lyxerr << "wrong idx " << idx() << ", max is " << lastidx()
244 << ". Trying to correct this." << endl;
247 if (pit() > lastpit()) {
248 lyxerr << "wrong par " << pit() << ", max is " << lastpit()
249 << ". Trying to correct this." << endl;
252 if (pos() > lastpos()) {
253 lyxerr << "wrong pos " << pos() << ", max is " << lastpos()
254 << ". Trying to correct this." << endl;
258 // The inset's getStatus() will return 'true' if it made
259 // a definitive decision on whether it want to handle the
260 // request or not. The result of this decision is put into
261 // the 'status' parameter.
262 if (inset().getStatus(*this, cmd, status)) {
272 BufferView & LCursor::bv() const
279 Buffer & LCursor::buffer() const
282 BOOST_ASSERT(bv_->buffer());
283 return *bv_->buffer();
289 BOOST_ASSERT(size() >= 1);
294 void LCursor::push(InsetBase & p)
296 push_back(CursorSlice(p));
300 void LCursor::pushLeft(InsetBase & p)
302 BOOST_ASSERT(!empty());
303 //lyxerr << "Entering inset " << t << " left" << endl;
309 bool LCursor::popLeft()
311 BOOST_ASSERT(!empty());
312 //lyxerr << "Leaving inset to the left" << endl;
313 inset().notifyCursorLeaves(*this);
321 bool LCursor::popRight()
323 BOOST_ASSERT(!empty());
324 //lyxerr << "Leaving inset to the right" << endl;
325 inset().notifyCursorLeaves(*this);
334 int LCursor::currentMode()
336 BOOST_ASSERT(!empty());
337 for (int i = size() - 1; i >= 0; --i) {
338 int res = operator[](i).inset().currentMode();
339 if (res != InsetBase::UNDECIDED_MODE)
342 return InsetBase::TEXT_MODE;
346 void LCursor::getDim(int & asc, int & des) const
349 BOOST_ASSERT(inset().asMathInset());
350 //inset().asMathInset()->getCursorDim(asc, des);
353 } else if (inTexted()) {
354 LyXFont const & realfont = text()->real_current_font;
355 asc = font_metrics::maxAscent(realfont);
356 des = font_metrics::maxDescent(realfont);
358 lyxerr << "should this happen?" << endl;
365 void LCursor::getPos(int & x, int & y) const
367 Point p = bv_funcs::getPos(*this);
373 void LCursor::paste(string const & data)
375 dispatch(FuncRequest(LFUN_PASTE, data));
379 void LCursor::resetAnchor()
386 bool LCursor::posLeft()
395 bool LCursor::posRight()
397 if (pos() == lastpos())
404 CursorSlice LCursor::anchor() const
406 BOOST_ASSERT(anchor_.size() >= size());
407 CursorSlice normal = anchor_[size() - 1];
408 if (size() < anchor_.size() && back() <= normal) {
409 // anchor is behind cursor -> move anchor behind the inset
416 CursorSlice LCursor::selBegin() const
420 return anchor() < back() ? anchor() : back();
424 CursorSlice LCursor::selEnd() const
428 return anchor() > back() ? anchor() : back();
432 DocIterator LCursor::selectionBegin() const
436 return anchor() < back() ? anchor_ : *this;
440 DocIterator LCursor::selectionEnd() const
444 return anchor() > back() ? anchor_ : *this;
448 void LCursor::setSelection()
451 // a selection with no contents is not a selection
453 #warning doesnt look ok
455 if (pit() == anchor().pit() && pos() == anchor().pos())
460 void LCursor::setSelection(DocIterator const & where, size_t n)
469 void LCursor::clearSelection()
478 int & LCursor::x_target()
484 int LCursor::x_target() const
490 void LCursor::clearTargetX()
497 void LCursor::info(std::ostream & os) const
499 for (int i = 1, n = depth(); i < n; ++i) {
500 operator[](i).inset().infoize(os);
504 prevInset()->infoize2(os);
505 // overwite old message
510 void LCursor::selHandle(bool sel)
512 //lyxerr << "LCursor::selHandle" << endl;
513 if (sel == selection())
521 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
523 os << "\n cursor: | anchor:\n";
524 for (size_t i = 0, n = cur.size(); i != n; ++i) {
525 os << " " << cur.operator[](i) << " | ";
526 if (i < cur.anchor_.size())
527 os << cur.anchor_[i];
529 os << "-------------------------------";
532 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
533 os << "------------------------------- | " << cur.anchor_[i] << "\n";
535 os << " selection: " << cur.selection_
536 << " x_target: " << cur.x_target_ << endl;
543 ///////////////////////////////////////////////////////////////////
545 // The part below is the non-integrated rest of the original math
546 // cursor. This should be either generalized for texted or moved
547 // back to mathed (in most cases to MathNestInset).
549 ///////////////////////////////////////////////////////////////////
551 #include "mathed/math_charinset.h"
552 #include "mathed/math_factory.h"
553 #include "mathed/math_gridinset.h"
554 #include "mathed/math_macroarg.h"
555 #include "mathed/math_mathmlstream.h"
556 #include "mathed/math_scriptinset.h"
557 #include "mathed/math_support.h"
558 #include "mathed/math_unknowninset.h"
560 //#define FILEDEBUG 1
563 bool LCursor::isInside(InsetBase const * p)
565 for (unsigned i = 0; i < depth(); ++i)
566 if (&operator[](i).inset() == p)
572 bool LCursor::openable(MathAtom const & t) const
583 // we can't move into anything new during selection
584 if (depth() >= anchor_.size())
586 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
593 void LCursor::setScreenPos(int x, int y)
596 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
601 void LCursor::plainErase()
607 void LCursor::markInsert()
613 void LCursor::markErase()
619 void LCursor::plainInsert(MathAtom const & t)
621 cell().insert(pos(), t);
626 void LCursor::insert(string const & str)
628 for_each(str.begin(), str.end(),
629 boost::bind(static_cast<void(LCursor::*)(char)>
630 (&LCursor::insert), this, _1));
634 void LCursor::insert(char c)
636 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
637 BOOST_ASSERT(!empty());
639 lyx::cap::selClearOrDel(*this);
640 insert(new MathCharInset(c));
642 text()->insertChar(*this, c);
647 void LCursor::insert(MathAtom const & t)
649 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
651 lyx::cap::selClearOrDel(*this);
656 void LCursor::insert(InsetBase * inset)
659 insert(MathAtom(inset));
661 text()->insertInset(*this, inset);
665 void LCursor::niceInsert(string const & t)
676 void LCursor::niceInsert(MathAtom const & t)
679 string safe = lyx::cap::grabAndEraseSelection(*this);
681 // enter the new inset and move the contents of the selection if possible
684 // be careful here: don't use 'pushLeft(t)' as this we need to
685 // push the clone, not the original
686 pushLeft(*nextInset());
692 void LCursor::insert(MathArray const & ar)
696 lyx::cap::eraseSelection(*this);
697 cell().insert(pos(), ar);
702 bool LCursor::backspace()
704 autocorrect() = false;
707 lyx::cap::selDel(*this);
712 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
719 MathUnknownInset * p = activeMacro();
720 if (p->name().size() > 1) {
721 p->setName(p->name().substr(0, p->name().size() - 1));
726 if (pos() != 0 && prevAtom()->nargs() > 0) {
727 // let's require two backspaces for 'big stuff' and
728 // highlight on the first
740 bool LCursor::erase()
742 autocorrect() = false;
747 lyx::cap::selDel(*this);
751 // delete empty cells if possible
752 if (pos() == lastpos() && inset().idxDelete(idx()))
755 // special behaviour when in last position of cell
756 if (pos() == lastpos()) {
757 bool one_cell = inset().nargs() == 1;
758 if (one_cell && depth() == 1 && lastpos() == 0)
764 inset().idxGlue(idx());
768 // 'clever' UI hack: only erase large items if previously slected
769 if (pos() != lastpos() && inset().nargs() > 0) {
784 DocIterator save = *this;
788 autocorrect() = false;
796 DocIterator save = *this;
800 autocorrect() = false;
805 void LCursor::macroModeClose()
809 MathUnknownInset * p = activeMacro();
811 string s = p->name();
815 // do nothing if the macro name is empty
819 string const name = s.substr(1);
821 // prevent entering of recursive macros
822 // FIXME: this is only a weak attempt... only prevents immediate
824 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
825 if (macro && macro->getInsetName() == name)
826 lyxerr << "can't enter recursive macro" << endl;
828 plainInsert(createMathInset(name));
832 string LCursor::macroName()
834 return inMacroMode() ? activeMacro()->name() : string();
838 void LCursor::handleNest(MathAtom const & a, int c)
840 //lyxerr << "LCursor::handleNest: " << c << endl;
842 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
845 pushLeft(*nextInset());
849 int LCursor::targetX() const
851 if (x_target() != -1)
860 void LCursor::setTargetX()
862 //for now this is good enough. A better solution would be to
863 //avoid this rebreak by setting cursorX only after drawing
864 bottom().text()->redoParagraph(bottom().pit());
871 bool LCursor::inMacroMode() const
875 MathUnknownInset const * p = prevAtom()->asUnknownInset();
876 return p && !p->final();
880 MathUnknownInset * LCursor::activeMacro()
882 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
886 void LCursor::pullArg()
891 MathArray ar = cell();
892 if (popLeft() && inMathed()) {
894 cell().insert(pos(), ar);
897 //formula()->mutateToText();
902 void LCursor::touch()
908 DocIterator::const_iterator it = begin();
909 DocIterator::const_iterator et = end();
910 for ( ; it != et; ++it)
916 void LCursor::normalize()
918 if (idx() >= nargs()) {
919 lyxerr << "this should not really happen - 1: "
920 << idx() << ' ' << nargs()
921 << " in: " << &inset() << endl;
923 idx() = min(idx(), lastidx());
925 if (pos() > lastpos()) {
926 lyxerr << "this should not really happen - 2: "
927 << pos() << ' ' << lastpos() << " in idx: " << idx()
929 WriteStream wi(lyxerr, false, true);
930 inset().asMathInset()->write(wi);
933 pos() = min(pos(), lastpos());
937 bool LCursor::goUpDown(bool up)
939 // Be warned: The 'logic' implemented in this function is highly
940 // fragile. A distance of one pixel or a '<' vs '<=' _really
941 // matters. So fiddle around with it only if you think you know
942 // what you are doing!
948 // check if we had something else in mind, if not, this is the future goal
949 if (x_target() == -1)
954 // try neigbouring script insets
958 MathScriptInset const * p = prevAtom()->asScriptInset();
959 if (p && p->has(up)) {
962 idx() = up; // the superscript has index 1
964 //lyxerr << "updown: handled by scriptinset to the left" << endl;
970 if (pos() != lastpos()) {
971 MathScriptInset const * p = nextAtom()->asScriptInset();
972 if (p && p->has(up)) {
976 //lyxerr << "updown: handled by scriptinset to the right" << endl;
982 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
987 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
988 // lyxerr << "updown: handled by brute find in the same cell" << endl;
992 // try to find an inset that knows better then we
994 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
996 if (inset().idxUpDown(*this, up)) {
997 // try to find best position within this inset
999 setCursor(bruteFind2(*this, xo, yo));
1003 // no such inset found, just take something "above"
1004 //lyxerr << "updown: handled by strange case" << endl;
1006 int ylow = up ? 0 : yo + 1;
1007 int yhigh = up ? yo - 1 : bv().workHeight();
1008 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1011 // any improvement so far?
1014 if (up ? ynew < yo : ynew > yo)
1018 // we should not come here.
1019 BOOST_ASSERT(false);
1023 void LCursor::handleFont(string const & font)
1025 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1029 safe = lyx::cap::grabAndEraseSelection(*this);
1032 if (lastpos() != 0) {
1033 // something left in the cell
1035 // cursor in first position
1037 } else if (pos() == lastpos()) {
1038 // cursor in last position
1041 // cursor in between. split cell
1042 MathArray::iterator bt = cell().begin();
1043 MathAtom at = createMathInset(font);
1044 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1045 cell().erase(bt, bt + pos());
1050 // nothing left in the cell
1058 void LCursor::message(string const & msg) const
1060 bv().owner()->getLyXFunc().setMessage(msg);
1064 void LCursor::errorMessage(string const & msg) const
1066 bv().owner()->getLyXFunc().setErrorMessage(msg);
1070 string LCursor::selectionAsString(bool label) const
1076 Buffer const & buffer = *bv().buffer();
1077 ParagraphList & pars = text()->paragraphs();
1079 // should be const ...
1080 pit_type startpit = selBegin().pit();
1081 pit_type endpit = selEnd().pit();
1082 size_t const startpos = selBegin().pos();
1083 size_t const endpos = selEnd().pos();
1085 if (startpit == endpit)
1086 return pars[startpit].asString(buffer, startpos, endpos, label);
1088 // First paragraph in selection
1089 string result = pars[startpit].
1090 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1092 // The paragraphs in between (if any)
1093 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1094 Paragraph & par = pars[pit];
1095 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1098 // Last paragraph in selection
1099 result += pars[endpit].asString(buffer, 0, endpos, label);
1104 #ifdef WITH_WARNINGS
1105 #warning and mathed?
1111 string LCursor::currentState()
1114 std::ostringstream os;
1120 return text()->currentState(*this);
1126 string LCursor::getPossibleLabel()
1128 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1132 Encoding const * LCursor::getEncoding() const
1139 // go up until first non-0 text is hit
1140 // (innermost text is 0 in mathed)
1141 for (s = size() - 1; s >= 0; --s)
1142 if (operator[](s).text())
1144 CursorSlice const & sl = operator[](s);
1145 LyXText & text = *sl.text();
1146 LyXFont font = text.getPar(sl.pit()).getFont(
1147 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1148 return font.language()->encoding();
1152 void LCursor::undispatched()
1154 disp_.dispatched(false);
1158 void LCursor::dispatched()
1160 disp_.dispatched(true);
1164 void LCursor::needsUpdate()
1170 void LCursor::noUpdate()
1172 disp_.update(false);