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];
126 LyXText * text = bottom.text();
129 DocIterator it = doc_iterator_begin(bottom.inset());
130 DocIterator const et = doc_iterator_end(bottom.inset());
132 double best_dist = std::numeric_limits<double>::max();;
133 DocIterator best_cursor = et;
135 for ( ; it != et; it.forwardPos()) {
136 // avoid invalid nesting when selecting
137 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
138 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
139 Point p = bv_funcs::getPos(it);
142 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
143 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
144 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
145 // '<=' in order to take the last possible position
146 // this is important for clicking behind \sum in e.g. '\sum_i a'
147 if (d <= best_dist) {
148 //lyxerr << "*" << endl;
156 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
157 if (best_cursor != et) {
158 cursor.setCursor(best_cursor);
168 // be careful: this is called from the bv's constructor, too, so
169 // bv functions are not yet available!
170 LCursor::LCursor(BufferView & bv)
171 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
172 selection_(false), mark_(false)
176 void LCursor::reset(InsetBase & inset)
179 push_back(CursorSlice(inset));
180 anchor_ = DocIterator(inset);
187 // this (intentionally) does neither touch anchor nor selection status
188 void LCursor::setCursor(DocIterator const & cur)
190 DocIterator::operator=(cur);
194 void LCursor::dispatch(FuncRequest const & cmd0)
196 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
197 << " cmd: " << cmd0 << '\n'
203 FuncRequest cmd = cmd0;
204 LCursor safe = *this;
206 for (; depth(); pop()) {
207 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
208 << cmd0 << endl << *this << endl;
209 BOOST_ASSERT(pos() <= lastpos());
210 BOOST_ASSERT(idx() <= lastidx());
211 BOOST_ASSERT(pit() <= lastpit());
213 // The common case is 'LFUN handled, need update', so make the
214 // LFUN handler's life easier by assuming this as default value.
215 // The handler can reset the update and val flags if necessary.
217 disp_.dispatched(true);
218 inset().dispatch(*this, cmd);
219 if (disp_.dispatched())
222 // it completely to get a 'bomb early' behaviour in case this
223 // object will be used again.
224 if (!disp_.dispatched()) {
225 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
227 disp_.dispatched(false);
232 DispatchResult LCursor::result() const
238 BufferView & LCursor::bv() const
245 Buffer & LCursor::buffer() const
248 BOOST_ASSERT(bv_->buffer());
249 return *bv_->buffer();
255 BOOST_ASSERT(depth() >= 1);
260 void LCursor::push(InsetBase & p)
262 push_back(CursorSlice(p));
266 void LCursor::pushLeft(InsetBase & p)
268 BOOST_ASSERT(!empty());
269 //lyxerr << "Entering inset " << t << " left" << endl;
275 bool LCursor::popLeft()
277 BOOST_ASSERT(!empty());
278 //lyxerr << "Leaving inset to the left" << endl;
279 inset().notifyCursorLeaves(*this);
287 bool LCursor::popRight()
289 BOOST_ASSERT(!empty());
290 //lyxerr << "Leaving inset to the right" << endl;
291 inset().notifyCursorLeaves(*this);
300 int LCursor::currentMode()
302 BOOST_ASSERT(!empty());
303 for (int i = depth() - 1; i >= 0; --i) {
304 int res = operator[](i).inset().currentMode();
305 if (res != InsetBase::UNDECIDED_MODE)
308 return InsetBase::TEXT_MODE;
312 void LCursor::getPos(int & x, int & y) const
314 Point p = bv_funcs::getPos(*this);
320 void LCursor::paste(string const & data)
322 dispatch(FuncRequest(LFUN_PASTE, data));
326 void LCursor::resetAnchor()
333 bool LCursor::posLeft()
342 bool LCursor::posRight()
344 if (pos() == lastpos())
351 CursorSlice LCursor::anchor() const
353 BOOST_ASSERT(anchor_.depth() >= depth());
354 CursorSlice normal = anchor_[depth() - 1];
355 if (depth() < anchor_.depth() && top() <= normal) {
356 // anchor is behind cursor -> move anchor behind the inset
363 CursorSlice LCursor::selBegin() const
367 return anchor() < top() ? anchor() : top();
371 CursorSlice LCursor::selEnd() const
375 return anchor() > top() ? anchor() : top();
379 DocIterator LCursor::selectionBegin() const
383 return anchor() < top() ? anchor_ : *this;
387 DocIterator LCursor::selectionEnd() const
391 return anchor() > top() ? anchor_ : *this;
395 void LCursor::setSelection()
398 // a selection with no contents is not a selection
400 #warning doesnt look ok
402 if (pit() == anchor().pit() && pos() == anchor().pos())
407 void LCursor::setSelection(DocIterator const & where, size_t n)
416 void LCursor::clearSelection()
425 int & LCursor::x_target()
431 int LCursor::x_target() const
437 void LCursor::clearTargetX()
444 void LCursor::info(std::ostream & os) const
446 for (int i = 1, n = depth(); i < n; ++i) {
447 operator[](i).inset().infoize(os);
451 prevInset()->infoize2(os);
452 // overwite old message
457 void LCursor::selHandle(bool sel)
459 //lyxerr << "LCursor::selHandle" << endl;
460 if (sel == selection())
468 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
470 os << "\n cursor: | anchor:\n";
471 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
472 os << " " << cur[i] << " | ";
473 if (i < cur.anchor_.depth())
474 os << cur.anchor_[i];
476 os << "-------------------------------";
479 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
480 os << "------------------------------- | " << cur.anchor_[i] << "\n";
482 os << " selection: " << cur.selection_
483 << " x_target: " << cur.x_target_ << endl;
490 ///////////////////////////////////////////////////////////////////
492 // The part below is the non-integrated rest of the original math
493 // cursor. This should be either generalized for texted or moved
494 // back to mathed (in most cases to MathNestInset).
496 ///////////////////////////////////////////////////////////////////
498 #include "mathed/math_charinset.h"
499 #include "mathed/math_factory.h"
500 #include "mathed/math_gridinset.h"
501 #include "mathed/math_macroarg.h"
502 #include "mathed/math_mathmlstream.h"
503 #include "mathed/math_scriptinset.h"
504 #include "mathed/math_support.h"
505 #include "mathed/math_unknowninset.h"
507 //#define FILEDEBUG 1
510 bool LCursor::isInside(InsetBase const * p)
512 for (unsigned i = 0; i < depth(); ++i)
513 if (&operator[](i).inset() == p)
519 bool LCursor::openable(MathAtom const & t) const
530 // we can't move into anything new during selection
531 if (depth() >= anchor_.depth())
533 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
540 void LCursor::setScreenPos(int x, int y)
543 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
548 void LCursor::plainErase()
554 void LCursor::markInsert()
560 void LCursor::markErase()
566 void LCursor::plainInsert(MathAtom const & t)
568 cell().insert(pos(), t);
573 void LCursor::insert(string const & str)
575 for_each(str.begin(), str.end(),
576 boost::bind(static_cast<void(LCursor::*)(char)>
577 (&LCursor::insert), this, _1));
581 void LCursor::insert(char c)
583 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
584 BOOST_ASSERT(!empty());
586 lyx::cap::selClearOrDel(*this);
587 insert(new MathCharInset(c));
589 text()->insertChar(*this, c);
594 void LCursor::insert(MathAtom const & t)
596 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
598 lyx::cap::selClearOrDel(*this);
603 void LCursor::insert(InsetBase * inset)
606 insert(MathAtom(inset));
608 text()->insertInset(*this, inset);
612 void LCursor::niceInsert(string const & t)
623 void LCursor::niceInsert(MathAtom const & t)
626 string const safe = lyx::cap::grabAndEraseSelection(*this);
628 // enter the new inset and move the contents of the selection if possible
631 // be careful here: don't use 'pushLeft(t)' as this we need to
632 // push the clone, not the original
633 pushLeft(*nextInset());
639 void LCursor::insert(MathArray const & ar)
643 lyx::cap::eraseSelection(*this);
644 cell().insert(pos(), ar);
649 bool LCursor::backspace()
651 autocorrect() = false;
654 lyx::cap::selDel(*this);
659 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
666 MathUnknownInset * p = activeMacro();
667 if (p->name().size() > 1) {
668 p->setName(p->name().substr(0, p->name().size() - 1));
673 if (pos() != 0 && prevAtom()->nargs() > 0) {
674 // let's require two backspaces for 'big stuff' and
675 // highlight on the first
687 bool LCursor::erase()
689 autocorrect() = false;
694 lyx::cap::selDel(*this);
698 // delete empty cells if possible
699 if (pos() == lastpos() && inset().idxDelete(idx()))
702 // special behaviour when in last position of cell
703 if (pos() == lastpos()) {
704 bool one_cell = inset().nargs() == 1;
705 if (one_cell && depth() == 1 && lastpos() == 0)
711 inset().idxGlue(idx());
715 // 'clever' UI hack: only erase large items if previously slected
716 if (pos() != lastpos() && inset().nargs() > 0) {
731 DocIterator save = *this;
735 autocorrect() = false;
743 DocIterator save = *this;
747 autocorrect() = false;
752 void LCursor::macroModeClose()
756 MathUnknownInset * p = activeMacro();
758 string const s = p->name();
762 // do nothing if the macro name is empty
766 string const name = s.substr(1);
768 // prevent entering of recursive macros
769 // FIXME: this is only a weak attempt... only prevents immediate
771 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
772 if (macro && macro->getInsetName() == name)
773 lyxerr << "can't enter recursive macro" << endl;
775 plainInsert(createMathInset(name));
779 string LCursor::macroName()
781 return inMacroMode() ? activeMacro()->name() : string();
785 void LCursor::handleNest(MathAtom const & a, int c)
787 //lyxerr << "LCursor::handleNest: " << c << endl;
789 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
792 pushLeft(*nextInset());
796 int LCursor::targetX() const
798 if (x_target() != -1)
807 void LCursor::setTargetX()
809 // For now this is good enough. A better solution would be to
810 // avoid this rebreak by setting cursorX only after drawing
811 bottom().text()->redoParagraph(bottom().pit());
819 bool LCursor::inMacroMode() const
823 MathUnknownInset const * p = prevAtom()->asUnknownInset();
824 return p && !p->final();
828 MathUnknownInset * LCursor::activeMacro()
830 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
834 void LCursor::pullArg()
839 MathArray ar = cell();
840 if (popLeft() && inMathed()) {
842 cell().insert(pos(), ar);
845 //formula()->mutateToText();
850 void LCursor::touch()
856 DocIterator::const_iterator it = begin();
857 DocIterator::const_iterator et = end();
858 for ( ; it != et; ++it)
864 void LCursor::normalize()
866 if (idx() >= nargs()) {
867 lyxerr << "this should not really happen - 1: "
868 << idx() << ' ' << nargs()
869 << " in: " << &inset() << endl;
871 idx() = min(idx(), lastidx());
873 if (pos() > lastpos()) {
874 lyxerr << "this should not really happen - 2: "
875 << pos() << ' ' << lastpos() << " in idx: " << idx()
877 WriteStream wi(lyxerr, false, true);
878 inset().asMathInset()->write(wi);
881 pos() = min(pos(), lastpos());
885 bool LCursor::goUpDown(bool up)
887 // Be warned: The 'logic' implemented in this function is highly
888 // fragile. A distance of one pixel or a '<' vs '<=' _really
889 // matters. So fiddle around with it only if you think you know
890 // what you are doing!
896 // check if we had something else in mind, if not, this is the future goal
897 if (x_target() == -1)
902 // try neigbouring script insets
906 MathScriptInset const * p = prevAtom()->asScriptInset();
907 if (p && p->has(up)) {
910 idx() = up; // the superscript has index 1
912 //lyxerr << "updown: handled by scriptinset to the left" << endl;
918 if (pos() != lastpos()) {
919 MathScriptInset const * p = nextAtom()->asScriptInset();
920 if (p && p->has(up)) {
924 //lyxerr << "updown: handled by scriptinset to the right" << endl;
930 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
935 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
936 // lyxerr << "updown: handled by brute find in the same cell" << endl;
940 // try to find an inset that knows better then we
942 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
944 if (inset().idxUpDown(*this, up)) {
945 // try to find best position within this inset
947 setCursor(bruteFind2(*this, xo, yo));
951 // no such inset found, just take something "above"
952 //lyxerr << "updown: handled by strange case" << endl;
954 int ylow = up ? 0 : yo + 1;
955 int yhigh = up ? yo - 1 : bv().workHeight();
956 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
959 // any improvement so far?
963 if (up ? ynew < yo : ynew > yo)
967 // we should not come here.
972 void LCursor::handleFont(string const & font)
974 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
978 safe = lyx::cap::grabAndEraseSelection(*this);
981 if (lastpos() != 0) {
982 // something left in the cell
984 // cursor in first position
986 } else if (pos() == lastpos()) {
987 // cursor in last position
990 // cursor in between. split cell
991 MathArray::iterator bt = cell().begin();
992 MathAtom at = createMathInset(font);
993 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
994 cell().erase(bt, bt + pos());
999 // nothing left in the cell
1007 void LCursor::message(string const & msg) const
1009 bv().owner()->getLyXFunc().setMessage(msg);
1013 void LCursor::errorMessage(string const & msg) const
1015 bv().owner()->getLyXFunc().setErrorMessage(msg);
1019 string LCursor::selectionAsString(bool label) const
1025 Buffer const & buffer = *bv().buffer();
1026 ParagraphList & pars = text()->paragraphs();
1028 // should be const ...
1029 pit_type startpit = selBegin().pit();
1030 pit_type endpit = selEnd().pit();
1031 size_t const startpos = selBegin().pos();
1032 size_t const endpos = selEnd().pos();
1034 if (startpit == endpit)
1035 return pars[startpit].asString(buffer, startpos, endpos, label);
1037 // First paragraph in selection
1038 string result = pars[startpit].
1039 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1041 // The paragraphs in between (if any)
1042 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1043 Paragraph & par = pars[pit];
1044 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1047 // Last paragraph in selection
1048 result += pars[endpit].asString(buffer, 0, endpos, label);
1053 #ifdef WITH_WARNINGS
1054 #warning and mathed?
1060 string LCursor::currentState()
1063 std::ostringstream os;
1069 return text()->currentState(*this);
1075 string LCursor::getPossibleLabel()
1077 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1081 Encoding const * LCursor::getEncoding() const
1088 // go up until first non-0 text is hit
1089 // (innermost text is 0 in mathed)
1090 for (s = depth() - 1; s >= 0; --s)
1091 if (operator[](s).text())
1093 CursorSlice const & sl = operator[](s);
1094 LyXText const & text = *sl.text();
1095 LyXFont font = text.getPar(sl.pit()).getFont(
1096 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1097 return font.language()->encoding();
1101 void LCursor::undispatched()
1103 disp_.dispatched(false);
1107 void LCursor::dispatched()
1109 disp_.dispatched(true);
1113 void LCursor::needsUpdate()
1119 void LCursor::noUpdate()
1121 disp_.update(false);
1125 LyXFont LCursor::getFont() const
1127 // HACK. far from being perfect...
1129 // go up until first non-0 text is hit
1130 // (innermost text is 0 in mathed)
1131 for (s = depth() - 1; s >= 0; --s)
1132 if (operator[](s).text())
1134 CursorSlice const & sl = operator[](s);
1135 LyXText const & text = *sl.text();
1136 LyXFont font = text.getPar(sl.pit()).getFont(
1137 bv().buffer()->params(),
1139 outerFont(sl.pit(), text.paragraphs()));
1145 void LCursor::fixIfBroken()
1147 // find out last good level
1148 LCursor copy = *this;
1149 size_t newdepth = depth();
1150 while (!copy.empty()) {
1151 if (copy.idx() > copy.lastidx()) {
1152 lyxerr << "wrong idx " << copy.idx()
1153 << ", max is " << copy.lastidx()
1154 << " at level " << copy.depth()
1155 << ". Trying to correct this." << endl;
1156 newdepth = copy.depth() - 1;
1158 else if (copy.pit() > copy.lastpit()) {
1159 lyxerr << "wrong pit " << copy.pit()
1160 << ", max is " << copy.lastpit()
1161 << " at level " << copy.depth()
1162 << ". Trying to correct this." << endl;
1163 newdepth = copy.depth() - 1;
1165 else if (copy.pos() > copy.lastpos()) {
1166 lyxerr << "wrong pos " << copy.pos()
1167 << ", max is " << copy.lastpos()
1168 << " at level " << copy.depth()
1169 << ". Trying to correct this." << endl;
1170 newdepth = copy.depth() - 1;
1174 // shrink cursor to a size where everything is valid, possibly
1176 while (depth() > newdepth) {
1178 lyxerr << "correcting cursor to level " << depth() << endl;