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());
124 CursorSlice bottom = cursor[0];
125 LyXText * text = bottom.text();
128 DocIterator it = doc_iterator_begin(bottom.inset());
129 DocIterator const et = doc_iterator_end(bottom.inset());
131 double best_dist = std::numeric_limits<double>::max();;
132 DocIterator best_cursor = et;
134 for ( ; it != et; it.forwardPos()) {
135 // avoid invalid nesting when selecting
136 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
137 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
138 Point p = bv_funcs::getPos(it);
141 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
142 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
143 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
144 // '<=' in order to take the last possible position
145 // this is important for clicking behind \sum in e.g. '\sum_i a'
146 if (d <= best_dist) {
147 //lyxerr << "*" << endl;
155 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
156 if (best_cursor != et) {
157 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] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
200 FuncRequest cmd = cmd0;
201 LCursor safe = *this;
203 for (; size(); pop()) {
204 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << 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 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
236 // This is, of course, a mess. Better create a new doc iterator and use
237 // this in Inset::getStatus. This might require an additional
238 // BufferView * arg, though (which should be avoided)
239 LCursor safe = *this;
241 for ( ; size(); pop()) {
242 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
243 if (idx() > lastidx()) {
244 lyxerr << "wrong idx " << idx() << ", max is " << lastidx()
245 << ". Trying to correct this." << endl;
248 if (pit() > lastpit()) {
249 lyxerr << "wrong par " << pit() << ", max is " << lastpit()
250 << ". Trying to correct this." << endl;
253 if (pos() > lastpos()) {
254 lyxerr << "wrong pos " << pos() << ", max is " << lastpos()
255 << ". Trying to correct this." << endl;
259 // The inset's getStatus() will return 'true' if it made
260 // a definitive decision on whether it want to handle the
261 // request or not. The result of this decision is put into
262 // the 'status' parameter.
263 if (inset().getStatus(*this, cmd, status)) {
273 BufferView & LCursor::bv() const
280 Buffer & LCursor::buffer() const
283 BOOST_ASSERT(bv_->buffer());
284 return *bv_->buffer();
290 BOOST_ASSERT(size() >= 1);
295 void LCursor::push(InsetBase & p)
297 push_back(CursorSlice(p));
301 void LCursor::pushLeft(InsetBase & p)
303 BOOST_ASSERT(!empty());
304 //lyxerr << "Entering inset " << t << " left" << endl;
310 bool LCursor::popLeft()
312 BOOST_ASSERT(!empty());
313 //lyxerr << "Leaving inset to the left" << endl;
314 inset().notifyCursorLeaves(*this);
322 bool LCursor::popRight()
324 BOOST_ASSERT(!empty());
325 //lyxerr << "Leaving inset to the right" << endl;
326 inset().notifyCursorLeaves(*this);
335 int LCursor::currentMode()
337 BOOST_ASSERT(!empty());
338 for (int i = size() - 1; i >= 0; --i) {
339 int res = operator[](i).inset().currentMode();
340 if (res != InsetBase::UNDECIDED_MODE)
343 return InsetBase::TEXT_MODE;
347 void LCursor::getDim(int & asc, int & des) const
350 BOOST_ASSERT(inset().asMathInset());
351 //inset().asMathInset()->getCursorDim(asc, des);
354 } else if (inTexted()) {
355 LyXFont const & realfont = text()->real_current_font;
356 asc = font_metrics::maxAscent(realfont);
357 des = font_metrics::maxDescent(realfont);
359 lyxerr << "should this happen?" << endl;
366 void LCursor::getPos(int & x, int & y) const
368 Point p = bv_funcs::getPos(*this);
374 void LCursor::paste(string const & data)
376 dispatch(FuncRequest(LFUN_PASTE, data));
380 void LCursor::resetAnchor()
387 bool LCursor::posLeft()
396 bool LCursor::posRight()
398 if (pos() == lastpos())
405 CursorSlice LCursor::anchor() const
407 BOOST_ASSERT(anchor_.size() >= size());
408 CursorSlice normal = anchor_[size() - 1];
409 if (size() < anchor_.size() && back() <= normal) {
410 // anchor is behind cursor -> move anchor behind the inset
417 CursorSlice LCursor::selBegin() const
421 return anchor() < back() ? anchor() : back();
425 CursorSlice LCursor::selEnd() const
429 return anchor() > back() ? anchor() : back();
433 DocIterator LCursor::selectionBegin() const
437 return anchor() < back() ? anchor_ : *this;
441 DocIterator LCursor::selectionEnd() const
445 return anchor() > back() ? anchor_ : *this;
449 void LCursor::setSelection()
452 // a selection with no contents is not a selection
454 #warning doesnt look ok
456 if (pit() == anchor().pit() && pos() == anchor().pos())
461 void LCursor::setSelection(DocIterator const & where, size_t n)
470 void LCursor::clearSelection()
479 int & LCursor::x_target()
485 int LCursor::x_target() const
491 void LCursor::clearTargetX()
498 void LCursor::info(std::ostream & os) const
500 for (int i = 1, n = depth(); i < n; ++i) {
501 operator[](i).inset().infoize(os);
505 prevInset()->infoize2(os);
506 // overwite old message
511 void LCursor::selHandle(bool sel)
513 //lyxerr << "LCursor::selHandle" << endl;
514 if (sel == selection())
522 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
524 os << "\n cursor: | anchor:\n";
525 for (size_t i = 0, n = cur.size(); i != n; ++i) {
526 os << " " << cur.operator[](i) << " | ";
527 if (i < cur.anchor_.size())
528 os << cur.anchor_[i];
530 os << "-------------------------------";
533 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
534 os << "------------------------------- | " << cur.anchor_[i] << "\n";
536 os << " selection: " << cur.selection_
537 << " x_target: " << cur.x_target_ << endl;
544 ///////////////////////////////////////////////////////////////////
546 // The part below is the non-integrated rest of the original math
547 // cursor. This should be either generalized for texted or moved
548 // back to mathed (in most cases to MathNestInset).
550 ///////////////////////////////////////////////////////////////////
552 #include "mathed/math_charinset.h"
553 #include "mathed/math_factory.h"
554 #include "mathed/math_gridinset.h"
555 #include "mathed/math_macroarg.h"
556 #include "mathed/math_mathmlstream.h"
557 #include "mathed/math_scriptinset.h"
558 #include "mathed/math_support.h"
559 #include "mathed/math_unknowninset.h"
561 //#define FILEDEBUG 1
564 bool LCursor::isInside(InsetBase const * p)
566 for (unsigned i = 0; i < depth(); ++i)
567 if (&operator[](i).inset() == p)
573 bool LCursor::openable(MathAtom const & t) const
584 // we can't move into anything new during selection
585 if (depth() >= anchor_.size())
587 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
594 void LCursor::setScreenPos(int x, int y)
597 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
602 void LCursor::plainErase()
608 void LCursor::markInsert()
614 void LCursor::markErase()
620 void LCursor::plainInsert(MathAtom const & t)
622 cell().insert(pos(), t);
627 void LCursor::insert(string const & str)
629 for_each(str.begin(), str.end(),
630 boost::bind(static_cast<void(LCursor::*)(char)>
631 (&LCursor::insert), this, _1));
635 void LCursor::insert(char c)
637 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
638 BOOST_ASSERT(!empty());
640 lyx::cap::selClearOrDel(*this);
641 insert(new MathCharInset(c));
643 text()->insertChar(*this, c);
648 void LCursor::insert(MathAtom const & t)
650 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
652 lyx::cap::selClearOrDel(*this);
657 void LCursor::insert(InsetBase * inset)
660 insert(MathAtom(inset));
662 text()->insertInset(*this, inset);
666 void LCursor::niceInsert(string const & t)
677 void LCursor::niceInsert(MathAtom const & t)
680 string safe = lyx::cap::grabAndEraseSelection(*this);
682 // enter the new inset and move the contents of the selection if possible
685 // be careful here: don't use 'pushLeft(t)' as this we need to
686 // push the clone, not the original
687 pushLeft(*nextInset());
693 void LCursor::insert(MathArray const & ar)
697 lyx::cap::eraseSelection(*this);
698 cell().insert(pos(), ar);
703 bool LCursor::backspace()
705 autocorrect() = false;
708 lyx::cap::selDel(*this);
713 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
720 MathUnknownInset * p = activeMacro();
721 if (p->name().size() > 1) {
722 p->setName(p->name().substr(0, p->name().size() - 1));
727 if (pos() != 0 && prevAtom()->nargs() > 0) {
728 // let's require two backspaces for 'big stuff' and
729 // highlight on the first
741 bool LCursor::erase()
743 autocorrect() = false;
748 lyx::cap::selDel(*this);
752 // delete empty cells if possible
753 if (pos() == lastpos() && inset().idxDelete(idx()))
756 // special behaviour when in last position of cell
757 if (pos() == lastpos()) {
758 bool one_cell = inset().nargs() == 1;
759 if (one_cell && depth() == 1 && lastpos() == 0)
765 inset().idxGlue(idx());
769 // 'clever' UI hack: only erase large items if previously slected
770 if (pos() != lastpos() && inset().nargs() > 0) {
785 DocIterator save = *this;
789 autocorrect() = false;
797 DocIterator save = *this;
801 autocorrect() = false;
806 void LCursor::macroModeClose()
810 MathUnknownInset * p = activeMacro();
812 string s = p->name();
816 // do nothing if the macro name is empty
820 string const name = s.substr(1);
822 // prevent entering of recursive macros
823 // FIXME: this is only a weak attempt... only prevents immediate
825 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
826 if (macro && macro->getInsetName() == name)
827 lyxerr << "can't enter recursive macro" << endl;
829 plainInsert(createMathInset(name));
833 string LCursor::macroName()
835 return inMacroMode() ? activeMacro()->name() : string();
839 void LCursor::handleNest(MathAtom const & a, int c)
841 //lyxerr << "LCursor::handleNest: " << c << endl;
843 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
846 pushLeft(*nextInset());
850 int LCursor::targetX() const
852 if (x_target() != -1)
861 void LCursor::setTargetX()
863 //for now this is good enough. A better solution would be to
864 //avoid this rebreak by setting cursorX only after drawing
865 bottom().text()->redoParagraph(bottom().pit());
872 bool LCursor::inMacroMode() const
876 MathUnknownInset const * p = prevAtom()->asUnknownInset();
877 return p && !p->final();
881 MathUnknownInset * LCursor::activeMacro()
883 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
887 void LCursor::pullArg()
892 MathArray ar = cell();
893 if (popLeft() && inMathed()) {
895 cell().insert(pos(), ar);
898 //formula()->mutateToText();
903 void LCursor::touch()
909 DocIterator::const_iterator it = begin();
910 DocIterator::const_iterator et = end();
911 for ( ; it != et; ++it)
917 void LCursor::normalize()
919 if (idx() >= nargs()) {
920 lyxerr << "this should not really happen - 1: "
921 << idx() << ' ' << nargs()
922 << " in: " << &inset() << endl;
924 idx() = min(idx(), lastidx());
926 if (pos() > lastpos()) {
927 lyxerr << "this should not really happen - 2: "
928 << pos() << ' ' << lastpos() << " in idx: " << idx()
930 WriteStream wi(lyxerr, false, true);
931 inset().asMathInset()->write(wi);
934 pos() = min(pos(), lastpos());
938 bool LCursor::goUpDown(bool up)
940 // Be warned: The 'logic' implemented in this function is highly
941 // fragile. A distance of one pixel or a '<' vs '<=' _really
942 // matters. So fiddle around with it only if you think you know
943 // what you are doing!
949 // check if we had something else in mind, if not, this is the future goal
950 if (x_target() == -1)
955 // try neigbouring script insets
959 MathScriptInset const * p = prevAtom()->asScriptInset();
960 if (p && p->has(up)) {
963 idx() = up; // the superscript has index 1
965 //lyxerr << "updown: handled by scriptinset to the left" << endl;
971 if (pos() != lastpos()) {
972 MathScriptInset const * p = nextAtom()->asScriptInset();
973 if (p && p->has(up)) {
977 //lyxerr << "updown: handled by scriptinset to the right" << endl;
983 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
988 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
989 // lyxerr << "updown: handled by brute find in the same cell" << endl;
993 // try to find an inset that knows better then we
995 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
997 if (inset().idxUpDown(*this, up)) {
998 // try to find best position within this inset
1000 setCursor(bruteFind2(*this, xo, yo));
1004 // no such inset found, just take something "above"
1005 //lyxerr << "updown: handled by strange case" << endl;
1007 int ylow = up ? 0 : yo + 1;
1008 int yhigh = up ? yo - 1 : bv().workHeight();
1009 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1012 // any improvement so far?
1015 if (up ? ynew < yo : ynew > yo)
1019 // we should not come here.
1020 BOOST_ASSERT(false);
1024 void LCursor::handleFont(string const & font)
1026 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1030 safe = lyx::cap::grabAndEraseSelection(*this);
1033 if (lastpos() != 0) {
1034 // something left in the cell
1036 // cursor in first position
1038 } else if (pos() == lastpos()) {
1039 // cursor in last position
1042 // cursor in between. split cell
1043 MathArray::iterator bt = cell().begin();
1044 MathAtom at = createMathInset(font);
1045 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1046 cell().erase(bt, bt + pos());
1051 // nothing left in the cell
1059 void LCursor::message(string const & msg) const
1061 bv().owner()->getLyXFunc().setMessage(msg);
1065 void LCursor::errorMessage(string const & msg) const
1067 bv().owner()->getLyXFunc().setErrorMessage(msg);
1071 string LCursor::selectionAsString(bool label) const
1077 Buffer const & buffer = *bv().buffer();
1078 ParagraphList & pars = text()->paragraphs();
1080 // should be const ...
1081 pit_type startpit = selBegin().pit();
1082 pit_type endpit = selEnd().pit();
1083 size_t const startpos = selBegin().pos();
1084 size_t const endpos = selEnd().pos();
1086 if (startpit == endpit)
1087 return pars[startpit].asString(buffer, startpos, endpos, label);
1089 // First paragraph in selection
1090 string result = pars[startpit].
1091 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1093 // The paragraphs in between (if any)
1094 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1095 Paragraph & par = pars[pit];
1096 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1099 // Last paragraph in selection
1100 result += pars[endpit].asString(buffer, 0, endpos, label);
1105 #ifdef WITH_WARNINGS
1106 #warning and mathed?
1112 string LCursor::currentState()
1115 std::ostringstream os;
1121 return text()->currentState(*this);
1127 string LCursor::getPossibleLabel()
1129 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1133 Encoding const * LCursor::getEncoding() const
1140 // go up until first non-0 text is hit
1141 // (innermost text is 0 in mathed)
1142 for (s = size() - 1; s >= 0; --s)
1143 if (operator[](s).text())
1145 CursorSlice const & sl = operator[](s);
1146 LyXText & text = *sl.text();
1147 LyXFont font = text.getPar(sl.pit()).getFont(
1148 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1149 return font.language()->encoding();
1153 void LCursor::undispatched()
1155 disp_.dispatched(false);
1159 void LCursor::dispatched()
1161 disp_.dispatched(true);
1165 void LCursor::needsUpdate()
1171 void LCursor::noUpdate()
1173 disp_.update(false);